标签:
一、列表:
列表的语法,以中括号开通和结尾,元素以逗号隔开。例如:name = []
列表是以下标取值,第一个元素下标是0,第二个元素下标是1,最后一个元素下标是-1.
1、增加
#name = ["zhangsan","lisi","wanger","liwu"]
#name[1] = "wang"#在列表name的下标为1的位置增加一个元素"wang",当然这个下标原来的元素也就没有了,也同样是修改
#print(name)
#[‘zhangsan‘, ‘wang‘, ‘wanger‘, ‘liwu‘]
插入法,name.insert(下标,要插入的元素名称)
#name.insert(0,"li")
#name.append("haha")#增加到最后一个
2、删除
#del name[1]#删(del并不是列表的专属,它可以也可以删除别的,例如直接删除变量)
#name.pop(0)#默认删除最后一个,可以加上列表下标
#name.remove("zhangsan")
3、修改
#name = ["zhangsan","lisi","wanger","liwu"]
#name[1] = "wang"#
#[‘zhangsan‘, ‘wang‘, ‘wanger‘, ‘liwu‘]
4、统计(count)
#name = ["zhangsan","lisi","wanger","liwu"]
#print(name.count("zhangsan"))
#1 #这里的1是代表zhangsan这个元素只有一个
5、索引(获取元素的下标)(index)
#name = ["zhangsan","lisi","wanger","liwu"]
#print(name.index("lisi"))
#1 #这里的1则表示lisi这个元素在列表中的下标是1
6、排序(sort)
#name = ["zhangsan","lisi","wanger","liwu","123","456"]
#print(name.sort())
#TypeError: unorderable types: int() < str()#python3里面不同类型的数据不能排序,python2.x里面可以排序,按照ASCII码排序。
7、翻转(reverse)
# name = ["zhangsan","lisi","wanger","liwu","3","2","1"]
# name.reverse()
# print(name)
#[‘1‘, ‘2‘, ‘3‘, ‘liwu‘, ‘wanger‘, ‘lisi‘, ‘zhangsan‘]
8、扩展(extend)name = ["zhangsan","lisi","wanger","liwu","3","2","1"]
name_2 = ["zhang","wang","li"]
name.extend(name_2)
print(name)
9、拷贝(浅copy和深copy)
浅copy
# name = ["zhangsan","lisi","wanger","liwu",["beidu","wangyi","sogou"]]
# name_2 = name.copy()
# print(name)
# print(name_2)
# name[0] = "wangmazi"
# name[4][0] = "beijing"
# print(name)
# print(name_2)
结果:
我们先打印name和name_2,发现已经copy完了,两个数据一模一样
[‘zhangsan‘, ‘lisi‘, ‘wanger‘, ‘liwu‘, [‘beidu‘, ‘wangyi‘, ‘sogou‘]]
[‘zhangsan‘, ‘lisi‘, ‘wanger‘, ‘liwu‘, [‘beidu‘, ‘wangyi‘, ‘sogou‘]]
然后我们在name里面修改zhangsan为wangmazi,发现name_2并没有跟着name变化,说明name_2已经独立为一个新的列表(列表的第一层数据已经完全被复制)。
但是,我们接着在name里面的的第二层列表修改baidu为beijing,发现name和name_2一模一样,这说明,列表只copy第一层数据,第二层开始就是共享一个数据(只复制 第一层)
[‘wangmazi‘, ‘lisi‘, ‘wanger‘, ‘liwu‘, [‘beijing‘, ‘wangyi‘, ‘sogou‘]]
[‘zhangsan‘, ‘lisi‘, ‘wanger‘, ‘liwu‘, [‘beijing‘, ‘wangyi‘, ‘sogou‘]]
深copy
# import copy(我们这里引用了copy这个模块,这里面的copy.copy跟列表中的copy一模一样)
#
# name = ["zhangsan","lisi","wanger","liwu",["beidu","wangyi","sogou"]]
# name_2 = copy.deepcopy(name) #注意这里,deepcopy意为深copy,
# print(name)
# print(name_2)
# name[0] = "wangmazi"
# name[4][0] = "beijing"
# print(name)
# print(name_2)
不废话,看结果
[‘zhangsan‘, ‘lisi‘, ‘wanger‘, ‘liwu‘, [‘beidu‘, ‘wangyi‘, ‘sogou‘]]
[‘zhangsan‘, ‘lisi‘, ‘wanger‘, ‘liwu‘, [‘beidu‘, ‘wangyi‘, ‘sogou‘]]
[‘wangmazi‘, ‘lisi‘, ‘wanger‘, ‘liwu‘, [‘beijing‘, ‘wangyi‘, ‘sogou‘]]
[‘zhangsan‘, ‘lisi‘, ‘wanger‘, ‘liwu‘, [‘beidu‘, ‘wangyi‘, ‘sogou‘]]
上面所示标红的字体看出,深copy会将更深层次的数据完完全全的copy一份。
Python之路-python数据类型(列表、字典、字符串、元祖)操作
标签:
原文地址:http://www.cnblogs.com/lei0213/p/5725501.html