首页 > 代码库 > Python 04-列表、

Python 04-列表、

列表

表名 = ["name1","name2"]

print(names[1:3])#切片

起始位置包括,结束位置不包括。会取1和2,不取3
names = ["name1","name2","name3","name4"]
print(names)
print(names[1],names[2])
print(names[1:3])#切片
print(names[-1])#取最后一个
print(names[-2:])#取最后两个
print(names[0:3])#取前两个

names.append("name5")#向数组里面插入
names.insert(1,"name6")#向数组1号位置插入
names.insert(3,"name7")#向数组3号位置插入

names[2]="name8"#2号元素改为name8

names.remove("name7")#删除元素name7
del names[2]#删除2号元素
names.pop()#默认删除最后一个,输入下标就删除第几号元素

print(names.index("name1"))#找name1在哪里
print(names[names.index("name1")])#把name1找到打印出来

names.append("name5")
names.append("name5")
print(names.count("name5"))#统计有多少个name5

names.reverse()#列表反转

names.sort()#按照首字母顺序排序

names2 = [1,2,3,4]
names.extend(names2)#把另一个列表并过来

names.clear()#列表清空


print(names)

 

浅copy

names = ["name1","name2","name3",["tom","jack"],"name4","name5"]

name2 = names.copy()#只copy第一层列表,第二层存的是指针,打印时候会从指针找原地址
print(names)
print(name2)
names[0]="名字1"
names[3][0]="alex"#name2里面也改了
print(names)
print(name2)

深copy

import copy
names = ["name1","name2","name3",["tom","jack"],"name4","name5"]

name2 = copy.deepcopy(names)#深copy,完全copy,第二层列表不跟着变化
print(names)
print(name2)
names[0]="名字1"
names[3][0]="alex"
print(names)
print(name2)

 

names = ["name1","name2","name3",["tom","jack"],"name4","name5"]
print(names[0:-1:2])#start,stop,step

 

 

Python 04-列表、