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放在后面
以上是python入門教學之列表操作的詳細內容。更多資訊請關注PHP中文網其他相關文章!