我的python之路-Day2
阿新 • • 發佈:2018-11-28
一.列表、元組操作
列表
1.通過下標訪問列表中的元素,從0開始
1 name = ["alex","lol","doat"] 2 >>> names[0] 3 "alex" 4 >>> names[2] 5 "lol" 6 >>> names[-1] 7 "dota" 8 >>> names[-2] #還可以倒著取 9 "lol"View Code
2.切片
1 names = ["alex","zhoujielun","eason","pig"View Code] 2 >>>names[1:2] #取下標1到2的元素,包括1不包括2 3 ["zhoujielun","eason"] 4 >>>names[:1] #從頭開始取,不需要寫0 5 ["alex","zhoujielun"] 6 >>>names[1:] #想取最後一個元素,-1不能寫 7 ["zhoujielun","eason","pig"] 8 >>>names[::2] #最後的2表示步長,每隔一個元素,就取一個 9 ["alex","eason"]
3.追加
1View Code>>>names = ['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy'] 2 >>>names.append('我是新來的') 3 names = ['Alex', 'Tenglan', 'Eric', 'Rain', 'Tom', 'Amy','我是新來的']
4.插入
1 >>>age = ['11','22','33'] 2 >>>age.insert(1,'我是新來的') #在1的元素前面插入 3 4 age = ['View Code11','我是新來的','22','33']
5. 修改
1 >>>names = ["alex","zhouzhou","jiejei"] 2 >>>names[1] = "該換人了" 3 names = ["alex","該換人了","jiejei"]View Code
6.刪除
1 >>>names = ["alex","zhouzhou","jiejie"] 2 >>>del names[1] 3 names = ["alex","jiejie"] 4 5 >>>names.pop() #刪除列表最後一個元素 6 names = ["alex"]View Code
7.擴充套件
1 >>>names = ["alex","zhouzhou"] 2 >>>b = ["sy"] 3 >>>names.extend(b) 4 names = ["alex","zhouzhou","sy"]View Code
8.統計
1 >>>names = ["alex","zhouzhou","juejie"] 2 >>>names.count("alex") 3 0View Code
9.排序&翻轉
1 >>> names 2 ['Alex', 'Amy', 'Amy', 'Tenglan', 'Tom', '1', '2', '3'] 3 >>> names.sort() 4 >>> names 5 ['1', '2', '3', 'Alex', 'Amy', 'Amy', 'Tenglan', 'Tom'] 6 7 >>> names.reverse() #反轉 8 >>> names 9 ['Tom', 'Tenglan', 'Amy', 'Amy', 'Alex', '3', '2', '1']View Code
10.獲取下標
1 >>>names = ["alex","zhouzhou","jiejie"] 2 >>>names.index("jiejie") 3 2View Code
11.拷貝
1 >>>names = ["alex","zhouzhou","jiejie"] 2 >>>names2 = names.copy() 3 names2 = ["alex","zhouzhou","jiejie"]View Code
拷貝真的這麼簡單嗎?
1 >>>names = ["zhangshaohan","zhoujielun"["alex","jack"],"xiaohong","wangba"] 2 >>>names2 = names.copy() 3 >>>print(names,names2) 4 >>>names[2][0] = "Alex" 5 >>>print(names) 6 >>>print(names2) 7 8 ['zhangshaohan', 'zhoujielun', ['alex', 'jack'], 'xiaohong', 'wangba'] ['zhangshaohan', 'zhoujielun', ['alex', 'jack'], 'xiaohong', 'wangba'] 9 ['zhangshaohan', 'zhoujielun', ['Alex', 'jack'], 'xiaohong', 'wangba'] 10 ['zhangshaohan', 'zhoujielun', ['Alex', 'jack'], 'xiaohong', 'wangba']View Code
PS:copy()只copy第一層淺copy,copy第二層的列表等,都不會被copy(只copy了一個記憶體地址)
1 >>>import copy 2 >>>names = ["zhangshaohan","zhoujielun",["alex","jack"],"xiaohong","wangba"] 3 >>>names2 = copy.deepcopy(names) 4 >>>print(names) 5 >>>print(names2) 6 >>>names[1] = "周杰倫" 7 >>>names[2][0] = "ALEX" 8 >>>print(names) 9 >>>print(names2) 10 11 ['zhangshaohan', 'zhoujielun', ['alex', 'jack'], 'xiaohong', 'wangba'] 12 ['zhangshaohan', 'zhoujielun', ['alex', 'jack'], 'xiaohong', 'wangba'] 13 ['zhangshaohan', '周杰倫', ['ALEX', 'jack'], 'xiaohong', 'wangba'] 14 ['zhangshaohan', 'zhoujielun', ['alex', 'jack'], 'xiaohong', 'wangba']View Code
元組
元組與列表近似,只是一旦建立,就不能修改,又稱只讀列表。
所以,它只有兩個方法:
- count
- index