#列表
names = ["aaa","bbb","ccc","ddd","eee","fff"]
#切片
1 print(names[0],"【1】") #取第一个值 2 print(names[1:3],"【-2】") #顾头不顾尾,忽略最后一个值 3 print(names[-3:-1],"【-3】") #负数还是从左到右边,一样忽略最后一个值 4 print(names[-3:],"【-4】") #取-3右边的所有值
#追加
1 names.append("fff") #追加 2 print(names,"【-5】")
#指定插入数据位置
1 names.insert(2,"gdr") #2原本为“ccc”的位置,插入“gdr”,依次往后靠 2 print(names,"【-6】")
#列表删除
1 names.remove("aaa") 2 print(names,"【-7】") 3 4 del names[2] #和names.pop(2)一样 5 print(names,"【-8】")
#查询位置
1 print(names.index("fff"),"【-9】") 2 print(names[names.index("fff")],"【-10】")
#统计重复值
print(names.count("fff"),"【-11】")
#列表多级和复制
1 names_2 = ["aaa",["haohao","zhuzhu"],"xxx"] 2 names_3 = names_2.copy() 3 names_2[0] = "大大" 4 names_2[1][0] = "大大二二" 5 print(names_2,"【-12】") 6 print(names_3,"【-13】")
#导入模块复制
1 import copy 2 names_4 = copy.copy(names_2) 3 print(names_4,"【-14】")
#列表循环
1 for i in names: 2 print("---",i,"---")
#列表步长
print(names[::2])
所有输出结果:
1 aaa 【1】 2 ['bbb', 'ccc'] 【-2】 3 ['ddd', 'eee'] 【-3】 4 ['ddd', 'eee', 'fff'] 【-4】 5 ['aaa', 'bbb', 'ccc', 'ddd', 'eee', 'fff', 'fff'] 【-5】 6 ['aaa', 'bbb', 'gdr', 'ccc', 'ddd', 'eee', 'fff', 'fff'] 【-6】 7 ['bbb', 'gdr', 'ccc', 'ddd', 'eee', 'fff', 'fff'] 【-7】 8 ['bbb', 'gdr', 'ddd', 'eee', 'fff', 'fff'] 【-8】 9 4 【-9】 10 fff 【-10】 11 2 【-11】 12 ['大大', ['大大二二', 'zhuzhu'], 'xxx'] 【-12】 13 ['aaa', ['大大二二', 'zhuzhu'], 'xxx'] 【-13】 14 ['大大', ['大大二二', 'zhuzhu'], 'xxx'] 【-14】 15 --- bbb --- 16 --- gdr --- 17 --- ddd --- 18 --- eee --- 19 --- fff --- 20 --- fff --- 21 ['bbb', 'ddd', 'fff']
#copy补充
1 names = ["name",["job",1000]] 2 #复制列表 3 p1 = names[:] 4 p2 = names[:] 5 #修改P1,P2的值 6 p1[0] = "gdr" 7 p2[0] = "dj" 8 9 p1[1][1] = 50 10 #打印查看结果 11 print(p1) 12 print(p2)
输出结果:
1 ['gdr', ['job', 50]] 2 ['dj', ['job', 50]]