1. 程式人生 > >Python學習—元組與集合

Python學習—元組與集合

card 技術分享 一次 ast lis 錯誤 錯誤信息 vpd mov

1.元組(tuple)

Python 的元組與列表類似,不同之處在於元組的元素不能修改。元組使用小括號,列表使用方括號。

1.元組定義

(1).定義一個tuple時,在定義的時候,tuple的元素就必須被確定下來,並且以後不可更改其值。

>>> tup1 = (‘this‘,‘is‘,‘aaaa‘)
>>> tup2 = (1,2,3,4)
>>> tup3 = (1,2,3,‘ssss‘)
>>> tup4 = ‘aa‘,‘bb‘,‘cc‘,‘dd‘;    #不用括號也可以定義元組
>>> type(tup4)
<class ‘tuple‘>      #可以看到tup4是元組

(2).需要註意:元組中只包含一個元素時,需要在元素後面添加逗號,否則括號會被當作運算符使用。

>>>tup1 = (50)
>>> type(tup1)     # 不加逗號,類型為整型
<class ‘int‘>
>>> tup1 = (50,)
>>> type(tup1)     # 加上逗號,類型為元組
<class ‘tuple‘>

這是因為括號()既可以表示tuple,又可以表示數學公式中的小括號,這就產生了歧義,因此,Python規定,這種情況下,小括號表示數學符號,因此tup1是整型。所以,只有1個元素的tuple定義時必須加一個逗號,,來消除歧義。

(3).創建空元組

>>> tup1 = ()      #用括號來創建空元組
>>> type(tup1)
<class ‘tuple‘>
>>> tup1
()              #可以看到元組裏沒有值,為空

(4).最後來看一個“可變的”tuple:

>>> t = (‘a‘, ‘b‘, [‘A‘, ‘B‘])
>>> t[2][0] = ‘X‘
>>> t[2][1] = ‘Y‘
>>> t
(‘a‘, ‘b‘, [‘X‘, ‘Y‘])

這個tuple定義的時候有3個元素,分別是‘a‘,‘b‘和一個list。不是說tuple一旦定義後就不可變了嗎?怎麽後來又變了?

我們先看看定義的時候tuple包含的3個元素:
技術分享圖片
當我們把list的元素‘A‘和‘B‘修改為‘X‘和‘Y‘後,tuple變為:
技術分享圖片
表面上看,tuple的元素確實變了,但其實變的不是tuple的元素,而是list的元素。tuple一開始指向的list並沒有改成別的list,所以,tuple所謂的“不變”是說,tuple的每個元素,指向永遠不變。即指向‘a‘,就不能改成指向‘b‘,指向一個list,就不能改成指向其他對象,但指向的這個list本身是可變的!
所以要創建一個內容也不變的tuple那就必須保證tuple的每一個元素本身也不能變,即是不可變數據類型。

2.訪問元組(索引)

元組可以使用中括號加下標索引來訪問元組中的值。

>>> tup1 = (‘this‘,‘is‘,‘aaaa‘)
>>> tup1[0]
‘this‘
>>> tup1[1]
‘is‘
>>> tup1[-1]
‘aaaa‘

3.刪除元組

元組中的元素值是不允許刪除的,但我們可以使用del語句來刪除整個元組

>>> tup4
(‘aa‘, ‘bb‘, ‘cc‘, ‘dd‘)
>>> del tup4
>>> tup4
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name ‘tup4‘ is not defined     #可以看到,刪除元組後再查看元組,錯誤信息提示元組未被定義

4.元組特性

(1).切片
和列表的切片一樣,使用中括號。

>>> tup3
(‘this‘, ‘is‘, ‘aaaa‘, 1, 2, 3, 4)
>>> tup3[:]
(‘this‘, ‘is‘, ‘aaaa‘, 1, 2, 3, 4)
>>> tup3[2:]
(‘aaaa‘, 1, 2, 3, 4)
>>> tup3[:-1]
(‘this‘, ‘is‘, ‘aaaa‘, 1, 2, 3)
>>> tup3[::-1]
(4, 3, 2, 1, ‘aaaa‘, ‘is‘, ‘this‘)
>>> tup3[::-2]
(4, 2, ‘aaaa‘, ‘this‘)

(2).重復
與列表一樣,使用符號*

>>> tup2
(1, 2, 3, 4)
>>> tup3 * 2
(‘this‘, ‘is‘, ‘aaaa‘, 1, 2, 3, 4, ‘this‘, ‘is‘, ‘aaaa‘, 1, 2, 3, 4)

(3).連接
與列表一樣,使用符號+

>>> tup1 = (‘this‘,‘is‘,‘aaaa‘)
>>> tup2 = (1,2,3,4)
>>> tup3 = tup1 + tup2
>>> tup3
(‘this‘, ‘is‘, ‘aaaa‘, 1, 2, 3, 4)

(4).成員操作符
與列表一樣,使用符號:in與not in

>>> tup3
(‘this‘, ‘is‘, ‘aaaa‘, 1, 2, 3, 4)
>>> ‘aaaa‘ in tup3
True
>>> 2 in tup3
True
>>> 4 not in tup3
False

5.元組內置函數

Python元組包含了以下內置函數
方法 描述
len(tuple) 計算元組元素個數。
max(tuple) 返回元組中元素最大值。
min(tuple) 返回元組中元素最小值。
tuple(seq) 將列表轉換為元組。

2.集合

沒有重復的數據,可以有不同數據類型。集合(set)是一個無序不重復元素的序列(所以不支持索引、切片、重復)。
可以使用大括號 { } 或者 set() 函數創建集合.
註意:創建一個空集合必須用 set() 而不是 { },因為 { } 是用來創建一個空字典。當用set()創建的集合有多個個元素時,需要將所有的元素再用括號括起來,否則會報錯。

1.集合定義

>>> sett = {1,2,3,4}   
>>> sett
{1, 2, 3, 4}
>>> s = {1,2,‘hh‘,‘ee‘}
>>> s
{1, 2, ‘ee‘, ‘hh‘}
>>> set1 = {‘apple‘, ‘orange‘, ‘pear‘, ‘banana‘}
>>> set1
{‘orange‘, ‘pear‘, ‘apple‘, ‘banana‘}
>>> set2  = {‘apple‘, ‘orange‘, ‘apple‘, ‘pear‘, ‘orange‘, ‘banana‘}    
>>> set2
{‘orange‘, ‘pear‘, ‘apple‘, ‘banana‘}     #集合的去重(集合中不允許有相同的數據,有也只會記錄一次,自動將重復的數據省略)

>>> ss = set(‘aa‘,‘bb‘)         
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: set expected at most 1 arguments, got 2    #set()定義多個元素的集合報錯

>>> ss = set((‘aa‘,‘bb‘))    #不會報錯
>>> ss                    
{‘aa‘, ‘bb‘}

定義空集合:

>>>  s = set()
>>> s
set()
>>> type(s)
<class ‘set‘>

2.添加元素:set.add(x)

向已經存在的集合中添加一個元素。如果元素已存在,則不進行任何操作,如果添加多個元素,則會報錯。

>>> set1 = {‘aa‘,‘ab‘,1,2}
>>> set1
{‘ab‘, 1, ‘aa‘, 2}
>>> set1.add(‘cc‘)
>>> set1
{1, 2, ‘cc‘, ‘ab‘, ‘aa‘}
>>> set1.add(8,9) 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: add() takes exactly one argument (2 given)

還有一個方法,也可以添加元素,且參數是列表,元組,字典,集合,字符串,不能是整數。語法格式如下:
set.update( x )
x 可以有多個,用逗號分開。

>>>set2 = {"Google", "RBQ", "Taobao"}
>>> set2
{‘RBQ‘, ‘Taobao‘, ‘Google‘}
>>> set2.update({1,3})
>>> set2
{1, 3, ‘Google‘, ‘Taobao‘, ‘RBQ‘}
>>> set2.update([1,4],[5,6])  
>>> set2
{1, 3, 4, 5, 6, ‘Google‘, ‘Taobao‘, ‘RBQ‘}
>>> set2.update(88) 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: ‘int‘ object is not iterable

另外再添加字符串的時候,還有一個有趣的現象。

>>> set2.update(‘s‘)
>>> set2
{1, 3, 4, 5, 6, ‘Google‘, ‘Taobao‘, ‘RBQ‘,‘s‘}
>>> set2.update(‘ssss‘)
>>> set2
{1, 3, 4, 5, 6, ‘Google‘, ‘Taobao‘, ‘RBQ‘,‘s‘}    #添加了‘ssss‘結果集合中沒有。
>>> set2.remove(‘s‘)
>>> set2
{1, ‘RBQ‘, 3, 4, ‘Taobao‘, ‘Google‘, 5, 6}      #刪除了元素‘s‘
>>> set2.update(‘ssss‘)
>>> set2
{1, ‘RBQ‘, 3, 4, ‘Taobao‘, ‘Google‘, 5, 6, ‘s‘}    #重新添加元素‘ssss‘結果集合出現了一個‘s‘
>>> set2.update(‘sss1‘)
>>> set2
{1, 3, 4, 5, 6, ‘RBQ‘, ‘Taobao‘, ‘1‘, ‘s‘, ‘Google‘}   #添加‘sss1‘結果出現了‘1‘
>>> set2.update(‘sa‘)  
>>> set2
{1, 3, 4, 5, 6, ‘RBQ‘, ‘Taobao‘, ‘1‘, ‘a‘, ‘s‘, ‘Google‘}   #添加‘sa‘出現了‘a‘

此外還有一個方法也是移除集合中的元素,且如果元素不存在,不會發生錯誤。格式如下所示:
set.discard( x )

>>> set1.discard(‘RBQ‘)
>>> set1
{‘ALI‘}
>>> set1.discard(‘ddd‘)
>>> set1
{‘ALI‘}

還可以彈出的方式來刪除集合中的一個元素,它會返回彈出的元素。語法格式如下:
set.pop()

>>> set2
{1, 3, 4, 5, 6, ‘RBQ‘, ‘Taobao‘, ‘1‘, ‘a‘, ‘s‘, ‘Google‘}
>>> set2.pop()
1
>>> set2
{3, 4, 5, 6, ‘RBQ‘, ‘Taobao‘, ‘1‘, ‘a‘, ‘s‘, ‘Google‘}
>>> set2.pop()
3
>>> set2.pop()
4

3.移除元素:set.remove(x)

向已經存在的集合中添加元素。如果元素不存在,則會發生錯誤。

>>> set1 = {"ALI", "RBQ", "TB"}
>>> set1
{‘RBQ‘, ‘ALI‘, ‘TB‘}
>>> set1.remove("TB")
>>> set1
{‘RBQ‘, ‘ALI‘}
>>> set1.remove("TTTT")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: ‘TTTT‘

4.成員操作符:in和not in

>>> set2
{5, 6, ‘RBQ‘, ‘Taobao‘, ‘1‘, ‘a‘, ‘s‘, ‘Google‘}
>>> ‘RBQ‘ in set2
True
>>> 2 not in set2
True
>>> 6 not in set2
False

5.集合運算:

    並集;s1.union(s2) 或者 s1 | s2
    交集:s1.intersection(s2) 或者 s1 | s2
    差集:s1.difference(s2) 或者 s1 - s2
         s2.denfference(s1) 或者 s2 - s1
    對差等分(並集-交集):s1.symmetric_difference(s2) 或者 s1 ^ s2

6.兩個集合函數

(1).求集合長度:len(set)

>>> set2
{5, 6, ‘RBQ‘, ‘Taobao‘, ‘1‘, ‘a‘, ‘s‘, ‘Google‘}
>>> len(set2)
8

(2).清空集合:set.clear()

>>> set2
{5, 6, ‘RBQ‘, ‘Taobao‘, ‘1‘, ‘a‘, ‘s‘, ‘Google‘}
>>> set2.clear()
>>> set2
set()

Python學習—元組與集合