1. 程式人生 > >python 列表,元組,字典,集合

python 列表,元組,字典,集合

列表:

序列是Python中最基本的資料結構。序列中的每個元素都分配一個數字 - 它的位置,或索引,第一個索引是0,第二個索引是1,依此類推。
Python有6個序列的內建型別,但最常見的是列表和元組。
序列都可以進行的操作包括索引,切片,加,乘,檢查成員。
此外,Python已經內建確定序列的長度以及確定最大和最小的元素的方法。
列表是最常用的Python資料型別,它可以作為一個方括號內的逗號分隔值出現。
列表的資料項不需要具有相同的型別
建立一個列表,只要把逗號分隔的不同的資料項使用方括號括起來即可。

# list
list1 = [1, 2, 3, 4, 5]
list2 = ["google", "Runoob", "a", 1, 2, 3]
list3 = ["a", "b", "c"]
print(list1[1])
print(list2[3])

列表使用半形中括號宣告 [ ]
更新列表的內容,可以直接使用

list1[i] = xxx

來更新,其中i為列表元素的下標
使用

del list[2]

來刪除列表元素
列表還支援拼接

squares = [1, 4, 9, 16, 25]
squares += [36, 49, 64, 81, 100]
 squares
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

0000000000000000000000000000000000000
元組:

Python 的元組與列表類似,不同之處在於元組的元素不能修改
元組使用小括號,列表使用方括號。
元組建立很簡單,只需要在括號中新增元素,並使用逗號隔開即可。

tup1 = ("google", "like", 1, 2, 3)
tup2 = "google", 1, 2, 3, 4, 5  #不用括號也可以

建立空元組:

tup1 = ();

元組中只包含一個元素時,需要在元素後面新增逗號,否則括號會被當作運算子使用:

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

對元組的修改:
元組內的元素不能修改,不過可以刪除整個元組、以及拼接兩個元組:

tup1 = (12, 34.56);
tup2 = ('abc', 'xyz')
 
# 以下修改元組元素操作是非法的。
# tup1[0] = 100
 
# 建立一個新的元組
tup3 = tup1 + tup2;
print (tup3)

#分割
tup = ('Google', 'Runoob', 1997, 2000)
 
print (tup)
del tup;
print ("刪除後的元組 tup : ")
print (tup)

0000000000000000000000000000000000000
字典:
字典是另一種可變容器模型,且可儲存任意型別物件。
字典的每個鍵值(key=>value)對用冒號(:)分割,每個對之間用逗號(,)分割,整個字典包括在花括號({})中 ,格式如下所示:

d = {key1 : value1, key2 : value2 }

鍵必須是唯一的,但值則不必。
值可以取任何資料型別,但鍵必須是不可變的,如字串,數字或元組。
一個簡單的字典例項:

dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
#或者如下建立字典
dict1 = { 'abc': 456 };
dict2 = { 'abc': 123, 98.6: 37 };

對字典的訪問:

dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
 
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])

修改及刪除字典內容:

dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}

dict['Age'] = 8;               # 更新 Age
dict['School'] = "菜鳥教程"  # 新增資訊
 
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
 
del dict['Name'] # 刪除鍵 'Name'
dict.clear()     # 清空字典
del dict         # 刪除字典
 
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])

在這裡會報異常,因為刪除字典後再列印會提示找不到
字典的特性:
字典值可以是任何的 python 物件,既可以是標準的物件,也可以是使用者定義的,但鍵不行。
兩個重要的點需要記住:
1)不允許同一個鍵出現兩次。建立時如果同一個鍵被賦值兩次,後一個值會被記住,如下例項:
2)鍵必須不可變,所以可以用數字,字串或元組充當,而用列表就不行,如下例項:

dict = {['Name']: 'Runoob', 'Age': 7}
 
print ("dict['Name']: ", dict['Name'])

以上例項輸出結果:

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    dict = {['Name']: 'Runoob', 'Age': 7}
TypeError: unhashable type: 'list'

0000000000000000000000000000000000000

集合:
集合(set)是一個無序的不重複元素序列。
可以使用大括號 { } 或者 set() 函式建立集合,注意:建立一個空集合必須用 set() 而不是 { },因為 { } 是用來建立一個空字典。
建立格式:

parame = {value01,value02,...}
#或者
set(value)

集合的運算

basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket)                      # 這裡演示的是去重功能
{'orange', 'banana', 'pear', 'apple'}
'orange' in basket                 # 快速判斷元素是否在集合內
True
'crabgrass' in basket
False
 
# 下面展示兩個集合間的運算.
...
a = set('abracadabra')
b = set('alacazam')
a                                  
{'a', 'r', 'b', 'c', 'd'}
a - b                              # 集合a中包含而集合b中不包含的元素
{'r', 'd', 'b'}
a | b                              # 集合a或b中包含的所有元素
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
a & b                              # 集合a和b中都包含了的元素
{'a', 'c'}
a ^ b                              # 不同時包含於a和b的元素
{'r', 'd', 'b', 'm', 'z', 'l'}

集合的基本操作:
1.新增元素,如果元素已經存在,那麼不進行任何操作

s.add( x )
thisset = set(("facebook", "linux", "hello"))
print(thisset)
thisset.add("valye")
print(thisset)

還有一個方法,也可以新增元素,且引數可以是列表,元組,字典等,語法格式如下:

s.update( x )

s.update(x)可以新增多個內容,用半形逗號隔開

print(thisset)
thisset.add("valye")
print(thisset)
thisset.update([1,4],[5,6])
print(thisset)

2.移除元素
語法格式如下:

s.remove( x )

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

s.discard( x )

我們也可以設定隨機刪除集合中的一個元素,語法格式如下:

s.pop() 

用法例項:

thisset = set(("Google", "Runoob", "Taobao", "Facebook"))
x = thisset.pop()
 
print(x)

多次執行測試結果都不一樣。
然而在互動模式,pop 是刪除集合的第一個元素(排序後的集合的第一個元素)。

thisset = set(("facebook", "linux", "hello"))
print(thisset)
thisset.add("valye")
print(thisset)
thisset.update([1,4],[5,6])
print(thisset)
thisset.remove("hello")
print(thisset)
thisset.discard(123)

3.計算集合元素的個數:

thisset.len()

4.清空集合:

thisset.clear()

5.判斷元素在集合眾是否存在
判斷元素 x 是否在集合 s 中,存在返回 True,不存在返回 False。
語法如下:

x in s

例項如下:

thisset = set(("Google", "Runoob", "Taobao"))
 "Runoob" in thisset
True
 "Facebook" in thisset
False