python的學習筆記/002-3(2018-5-20)
阿新 • • 發佈:2018-05-20
列表(list)的常見操作群集類型
names.reverse();names,sort();names.extend()
群集類型 | 列表 | 元組 | 字典 | 集合 |
---|---|---|---|---|
list | tuple | dict | set |
1.列表
列表的類型是list,特點為有序,具備索引,內容與長度可以變動。要創建列表,可以使用[]直接表示法,列表中每個元素使用逗號分隔開。
列表的常見操作
(1) 元素的切片
names=["Zhangfei","Guanyu","Liubie","Zhaoyun","Machoa","Jiangwei","Mashu","Zhaoyun"] print(names) print(names[0]) # 切位置0的元素 print(names[0:4]) # 切出位置0~3的元素 print(names[-1]) # 切出最後一位的元素 print(names[-3:]) # 切片,左取右不取`` print(names[0:-1:2]) # 有間隔的切片 for i in names: print(i) # 循環的切片方法,這個i就代表了列表中的元素
(2) 列表的增,改,刪
names.append();names.insert();names.remove();names.pop()
names=["Zhangfei","Guanyu","Liubie","Zhaoyun","Machoa","Jiangwei","Masu","Zhaoyun"] print(names) names.append("Zhugelaing") # [增]-----在列表末尾 追加 諸葛亮 print(names) names.insert(3,"daqiao") # [增]-----在列表中的位置3 插入 大喬 print(names) names[2]="zhouyu" #[改]----- 將劉備 替換 為周瑜 print(names) # names.remove("Masu") # [刪]-----刪除 馬謖 (有三種常用的方法) # del names[-3] print(names.pop(-3)) print(names)
(3) 列表的查,統計
names.index();names.count()
names=["Zhangfei","Guanyu","Liubie","Zhaoyun","Machoa","Jiangwei","Masu","Zhaoyun"]
print(names)
print(names.index("Zhaoyun")) # 獲取下標,趙雲有倆個但是卻只查到了列表裏的第一個????
print(names[names.index("Zhaoyun")])
print(names.count("Zhaoyun") ) # 統計 列表中趙雲的個數
(4) 列表的反轉,排序,合並
names=["Zhangfei","Guanyu","Liubie","Zhaoyun","Machoa","Jiangwei","Masu","Zhaoyun"]
print(names)
names.reverse() # 將列表 反轉
print(names)
names.sort() # 將列表按照默認的utf-8格式 排序
print(names)
names2=["Chaochao","Simayi","Diewei","Xiahuodong","Xuchu"]
names.extend(names2 ) # 合並倆個列表,但是合並的列表仍然存在
print(names)
(5) 列表的復制
names.copy();copy.copy();copy.deepcopy()
import copy # 需要為深copy引入模塊
names=["Zhangfei","Guanyu","Liubie","Zhaoyun",["zhouyu","daqiao"],"Machoa","Jiangwei","Masu","Zhaoyun"]
names1=names # 完全就是二者相等
names2=names.copy() # 淺copy,第二個列表裏其實copy的是一個地址,可以用來實現一個聯合賬戶的功能
names3=copy.copy(names) # 三種不同的實現方法
names4=names[:]
names5=copy.deepcopy(names) # 深copy一般不用因為會占用更多的空間
names[2]="劉邦" # 將位置2的元素改為劉邦
names[4][0]="小喬" # 將位置4列表裏的位置0元素改為大喬
print(names) # 比較幾種不同的復制
print(names1)
print(names2)
print(names3)
print(names4)
print(names5)
(6) 列表的清除
names.clear()
names=["Zhangfei","Guanyu","Liubie","Zhaoyun","Machoa","Jiangwei","Masu","Zhaoyun"]
print(names)
names.clear()
print(names)
python的學習筆記/002-3(2018-5-20)