python列表操作——增 append:追加一條數據到列表的最後 python列表操作——刪 如果當pop()中帶入了參數,其效果等同於del python列表操作——改 python列表操作——查 當下標為負數時,則從右邊開始取 列表其他操作: ...
python列表操作——增
append:追加一條數據到列表的最後
name = ["Zhangsan","XiongDa","Lisi"] name.append("wangwu") print name 輸出結果: ['Zhangsan', 'XiongDa', 'Lisi', 'wangwu']
insert:指定位置插入一條數據
name = ["Zhangsan","XiongDa","Lisi"] name.insert(1,"wangwu") #在下標為1的位置插入一條數據“wangwu” print name 輸出結果: ['Zhangsan', 'wangwu', 'XiongDa', 'Lisi']
python列表操作——刪
name = ["Zhangsan","XiongDa","Lisi"] name.remove("Lisi") #刪除指定的數據 print name 輸出結果: ['Zhangsan', 'XiongDa']
name = ["Zhangsan","XiongDa","Lisi"] del name[0] #刪掉下標為0的一條數據 print name 輸出結果: ['XiongDa', 'Lisi']
name = ["Zhangsan","XiongDa","Lisi"] name.pop() #刪除最後一條數據 print name 輸出結果: ['Zhangsan', 'XiongDa']
如果當pop()中帶入了參數,其效果等同於del
Name.pop(1) == del name[1]
python列表操作——改
name = ["Zhangsan","XiongDa","Lisi"] name[1] = "wangwu" print name 輸出結果: ['Zhangsan', 'wangwu', 'Lisi']
python列表操作——查
name = ["Zhangsan","XiongDa","Lisi","wangwu"] print(name[1]) #直接取出下標為1的數據 輸出結果: XiongDa
name = ["Zhangsan","XiongDa","Lisi","wangwu"] print(name[0:2]) #取出從下標0到下標1的數據,不包括2(顧頭不顧尾) 輸出結果: ['Zhangsan', 'XiongDa']
當下標為負數時,則從右邊開始取
name = ["Zhangsan","XiongDa","Lisi","wangwu"] print(name[-1]) #直接取出下標為1的數據 輸出結果: wangwu
name = ["Zhangsan","XiongDa","Lisi","wangwu"] print(name[-3:-1]) #從倒數第三個開始取,取到倒數第二個,因為不包括-1 輸出結果: ['XiongDa', 'Lisi']
name = ["Zhangsan","XiongDa","Lisi","wangwu"] print(name[-3:]) #從倒數第三個開始取,取到倒數第一個 輸出結果: ['XiongDa', 'Lisi', 'wangwu'] 同理從左邊開始取時 name[0:3] == name[:3]
列表其他操作:
name = ["Zhangsan","XiongDa","Lisi","wangwu","Lisi"] name.count("Lisi") #統計Lisi出現的次數 name.clear() #清空數據 name.reverse() #反轉列表 name.sort() #正向排序 name2 = ["1","2"] name.extend(name2) #兩個數組合併,name2放在後面