Python 列表、元組、字典及集合操作詳解


一、列表

  • 列表是Python中最基本的數據結構,是最常用的Python數據類型,列表的數據項不需要具有相同的類型
  • 列表是一種有序的集合,可以隨時添加和刪除其中的元素
  • 列表的索引從0開始

1、創建列表

>>> list1 = ['python', 2018, 'python3', 1994]
>>> list1
['python', 2018, 'python3', 1994]

>>> list2 = [1, 2, 3, 4]
>>> list2
[1, 2, 3, 4]

>>> list3 = ['a', 'b', 'c', 'd']
>>> list3
['a', 'b', 'c', 'd']

2、獲取列表元素個數

>>> len(list1)
4

3、訪問列表中的值

(1)使用索引來訪問列表中的值,列表的索引從0開始:

>>> list1[0]
'python'
>>> list1[1]
2018
>>> list1[2]
'python3'
>>> list1[3]
1994
>>> list1[4]
Traceback (most recent call last):
  File "<input>", line 1, in <module>
IndexError: list index out of range

注意:當索引超出范圍時,Python會報一個IndexError錯誤,所以,要確保索引不要越界,記得最后一個元素的索引是len(list1) - 1。

(2)還可以獲取列表最后一個元素:

>>> list1[-1]
1994

以此類推,可以獲取倒數第2個、倒數第3個、倒數第4個:

>>> list1[-2]
'python3'
>>> list1[-3]
2018
>>> list1[-4]
'python'
>>> list1[-5]
Traceback (most recent call last):
  File "<input>", line 1, in <module>
IndexError: list index out of range

當然,倒數第5個元素已越界,需要注意一下。

(3)切片

截取列表前3個元素:

>>> list1[0:3]
['python', 2018, 'python3']

>>> list1[:3]   #如果第一個索引是0,可以省略
['python', 2018, 'python3']

倒數切片:

>>> list1[-2:]  #獲取后2個元素
['python3', 1994]

>>> list1[-2:-1]
['python3']

前4個元素,每兩個取一個:

>>> list1[:4:2]
['python', 'python3']

所有元素,每3個取一個:

>>> list1[::3]
['python', 1994]

原樣復制一個列表:

>>> list1[:]
['python', 2018, 'python3', 1994]

4、合並列表

>>> list4 = list2 + list3
>>> list4
[1, 2, 3, 4, 'a', 'b', 'c', 'd']

5、更新列表

>>> list1
['python', 2018, 'python3', 1994]
>>> list1[1] = 2017
>>> list1
['python', 2017, 'python3', 1994]

6、刪除列表

>>> del list4

7、清空列表

>>> list1
['python', 2017, 'python3', 1994]
>>> list1.clear()
>>> list1
[]

8、列表操作的函數和方法

列表操作包含以下函數:

cmp(list1, list2)  #比較兩個列表的元素 
len(list)         #列表元素個數 
max(list)       #返回列表元素最大值 
min(list)      #返回列表元素最小值 
list(seq)     #將元組轉換為列表     

列表操作包含以下方法:

list.append(obj)       #在列表末尾添加新的對象
list.count(obj)      #統計某個元素在列表中出現的次數
list.extend(seq)      #在列表末尾一次性追加另一個序列中的多個值(用新列表擴展原來的列表)
list.index(obj)      #從列表中找出某個值第一個匹配項的索引位置
list.insert(index, obj) #將對象插入列表
list.pop(obj=list[-1]) #移除列表中的一個元素(默認最后一個元素),並且返回該元素的值
list.remove(obj)     #移除列表中某個值的第一個匹配項
list.reverse()      #反向列表中元素
list.sort([func])    #對原列表進行排序

 

 

二、元組

元組(tuple)和列表(list)非常類似,但是元組一旦初始化就不能修改,且元組使用小括號而列表使用中括號。

1、創建元組

>>> tup1 = ('python', 2018, 'python3', 1994)
>>> tup1
('python', 2018, 'python3', 1994)

>>> tup2 = (1, 2, 3, 4)
>>> tup2
(1, 2, 3, 4)

>>> tup3 = ('a', 'b', 'c', 'd')
>>> tup3
('a', 'b', 'c', 'd')

注意:元組中只包含一個元素時,需要在元素后面添加逗號來消除歧義

>>> tup4 = ('hello',)

2、合並元組

>>> tup5 = tup2 + tup3
>>> tup5
(1, 2, 3, 4, 'a', 'b', 'c', 'd')

3、刪除元組

>>> del tup5
>>> tup5 #此時tup5已不存在,所有報錯
Traceback (most recent call last):
  File "<input>", line 1, in <module>
NameError: name 'tup5' is not defined

元組的操作基本與列表的操作一直,除了不能修改元組本身外。

三、字典

  • 字典是另一種可變容器模型,且可存儲任意類型對象,如字符串、數字、元組等其他容器模型
  • 字典在其他語言中也稱為map,使用鍵-值(key-value)存儲,具有極快的查找速度
  • 字典中鍵是唯一的,如果重復最后的一個鍵值對會替換前面的,值不需要唯一

1、創建字典

>>> dict1 = {'a': 1, 'b': 2, 'b': '3'}
>>> dict1
{'a': 1, 'b': '3'}  #因為鍵存在相同,所以后面的鍵值替換了前面的鍵值

>>> dict2 = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
>>> dict2
{'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}

>>> dict3 = { 'abc': 123, 98.6: 37 }
>>> dict3
{'abc': 123, 98.6: 37}

2、訪問字典中的值

>>> dict2['Beth']
'9102'

>>> dict2['Beth1']  # 如果字典中沒有的鍵訪問值,會輸出以下錯誤
Traceback (most recent call last):
  File "<input>", line 1, in <module>
KeyError: 'Beth1'

3、修改字典

>>> dict1
{'a': 1, 'b': '3'}
>>> dict1['b'] = 666
>>> dict1
{'a': 1, 'b': 666}

4、刪除字典元素

能刪單一的元素也能清空字典,並且可以直接刪除字典

>>> dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
>>> dict
{'Name': 'Zara', 'Age': 7, 'Class': 'First'}
>>> del dict['Name']  #刪除鍵是'Name'的條目
>>> dict
{'Age': 7, 'Class': 'First'}
>>> dict.clear()  #清空詞典所有條目
>>> dict
{}
>>> del dict  #刪除詞典

5、字典內置函數和方法

Python字典包含了以下內置函數:

cmp(dict1, dict2)  #比較兩個字典元素。
len(dict)          #計算字典元素個數,即鍵的總數。
str(dict)          #輸出字典可打印的字符串表示。
type(variable)     #返回輸入的變量類型,如果變量是字典就返回字典類型。        

Python字典包含了以下內置方法:

dict.clear()                     #刪除字典內所有元素
dict.copy()                   #返回一個字典的淺復制
radiansdict.fromkeys()            #創建一個新字典,以序列seq中元素做字典的鍵,val為字典所有鍵對應的初始值
dict.get(key, default=None)        #返回指定鍵的值,如果值不在字典中返回default值
dict.has_key(key)                  #如果鍵在字典dict里返回true,否則返回false
dict.items()                  #以列表返回可遍歷的(鍵, 值) 元組數組
dict.keys()                  #以列表返回一個字典所有的鍵
dict.setdefault(key, default=None)    #和get()類似, 但如果鍵不已經存在於字典中,將會添加鍵並將值設為default
dict.update(dict2)                  #把字典dict2的鍵/值對更新到dict里
dict.values()                     #以列表返回字典中的所有值

四、集合

集合(set)是一個無序不重復元素的序列。

可以使用大括號 { } 或者 set() 函數創建集合,注意:創建一個空集合必須用 set() 而不是 { },因為 { } 是用來創建一個空字典。

1、創建集合

#創建一個空集合
>>> set1 = set()
>>> set1
set()

#創建一個具有數據的集合
>>> set2 = {1, 'a', 'apple', 11.22}
>>> set2
{11.22, 1, 'apple', 'a'}

>>> set3 = set([1, 2, 3])
>>> set3
{1, 2, 3}

2、判斷元素是否在集合內

>>> 'apple' in set2
True
>>> 'apple' not in set2
False

3、添加元素

#將值添加到集合中,如果值存在,則不作任何操作
>>> set2.add('car')
>>> set2
{1, 'apple', 'car', 11.22, 'a'}

#另外一種添加方式,參數可以是列表、元組、字典等
>>> set2.update({2,3})
>>> set2
{1, 'apple', 2, 3, 'car', 11.22, 'a'}

>>> set2.update([1,4],[5,6])
>>> set2
{1, 'apple', 2, 3, 4, 5, 6, 'car', 11.22, 'a'}

4、刪除元素 

>>> set2.remove('car')
>>> set2
{1, 'apple', 2, 3, 4, 5, 6, 11.22, 'a'}

>>> set2.remove('hello') #如果元素不存在會發生錯誤
Traceback (most recent call last):
  File "<input>", line 1, in <module>
KeyError: 'hello'

#這種方式如果元素不存在不會發生錯誤
>>> set2.discard('hello')

5、計算集合元素個數

>>> len(set2)
9

6、清空集合

>>> set2.clear()
>>> set2
set()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM