1. 程式人生 > >Python學習日記(2)Python內建集合及操作

Python學習日記(2)Python內建集合及操作

進行 添加 依然 修改 lis ever 原來 合並 and

  列表

 列表是零個或多個Python對象的一個序列,這些對象通常稱之為項;

 列表示例:

[]    #An empty list

["test"]    #A list of one string 

["test","python"]     #A list of two string

["test","python",10]    #A list of two string and an int

["test",["python",10]]    #A list with a nested list

和字符串一樣,可以對列表進行切片和鏈接,但是註意,切片和鏈接後,返回的依然是一個列表;

與字符串不同的是,列表是可變的(字符串不可變),這意味著,你可以針對列表進行替換,插入,刪除等操作;

當然,如果你對列表進行了操作(比如替換,插入,刪除),這意味著2個後果:

  1,你改變了列表的結構

  2,操作後返回的列表是一個新的列表而不是原列表

如果你想趣味的記住列表的一些操作,你可以認為,Python針對列表開發了一個"修改器":

讓我們看看"修改器"的功能有什麽:

test_list = []    #創建空列表

test_list.append(2) #列表中添加項:2

test_list.append(33) #列表中添加項:33

test_list.pop() #
彈出列表中最後一個項(我習慣理解是剪切,因為彈出的項可以用) test_list.insert(0,25) #在列表下標0的位置插入項:25 test_list.insert(1,66) #在列表下標1的位置插入項:66 test_list.sort() #列表從小到大排列 test_list.sort(severse=True) #列表從大到小排序 test_list.severse() #將列表逆序,不改變列表中項原來的順序 test_list.remove(25) #刪除列表中的項:25 test_list.count(25) #返回列表中25出現的次數 test_list.extend(list)
#將list合並到test_list中 "".join(test_list) #將test_list列表內的項轉為字符串 "python_string".split() #將字符串切片為列表

  元組

元組是項的一個不可變序列,且元組中最少包含2個項,表示方法是用括弧括起來,元組實際上與列表一樣,只不過元組沒有“修改器”,元組是不可變序列;

(33,44) #一個元組,包含項:33和44

當然,上圖的元組,你沒發用列表的修改器方法進行修改。

  遍歷序列

for循環用來遍歷一個序列(字符串,元組,列表)中的項,比如遍歷一個列表:

test1_list = [22,33,44,"python"]

for item in test1_list:
    print(item)

---------------------------------------------
22
33
44
python
[Finished in 0.2s]

  字典

字典包含零個或多個條目,每一個條目都一個唯一的鍵和對應的值相關聯。

鍵一般是字符串或者整數,而值可以是Python中的任何對象;

字典的鍵和值被包含在一對花括號中:

{} 

{"name":"python"}

{"name":"python","id":6520}

{"name":"python","id":6520,"item":[66,88]}

當然,字典和列表一樣,是可變類型,與元組不可變類型不同,Python中同樣為可變類型字典也添加了“修改器”:

test_dict = {} #創建一個空字典

test_dict["name"] = "python"  #字典中添加鍵name和對應值python

#>>>{‘name‘: ‘python‘}

test_dict["id"] = 18 #字典中添加鍵id和對應的值18

#>>>{‘name‘: ‘python‘, ‘id‘: 18}

test_dict.get("id") #查詢字典中鍵id對應的值

del test_dict["id"] #刪除字典中鍵id和其對應的值

  遍歷字典

test_dict = {name: python, id: 18}

for a in test_dict.keys():    #遍歷字典中所有的鍵
    print(a)

for b in test_dict.values(): #遍歷字典中所有的值
    print(b)

for c in test_dict.items():  #遍歷字典中每一對鍵和值,並按對遍歷後生成元組出儲存
    print(c)

---------------------------------------------
name
id
python
18
(name, python)
(id, 18)
[Finished in 0.1s]

  字典的pop()和get()方法

dict_test = {"id":6520}

a = dict_test.pop("ss","未找到值")

#>>>未找到值

b = dict_test.pop("id","未找到值")

#>>>6520

print(dict_test)

#>>>{}

對於字典來說,get()和pop()方法可以接收2個參數,一個鍵和一個默認值,搜索或者彈出失敗,會返回默認值;

如果搜索成功或彈出成功,則會返回搜索和彈出鍵對應的值;

Python學習日記(2)Python內建集合及操作