在Python中用[]来表示列表,并用逗号隔开其中的元素。
1、访问列表元素
name=["zhangsan","lisi","ljy"] print(name[0])#索引从0开始而不是1 print(name[-1])#返回最后一个元素
2、修改列表元素
name=["zhangsan","lisi","ljy"] print(name) name[1]="wangwu" print(name)
3、添加列表元素
name=["zhangsan","lisi","ljy"] print(name) name.append("qxc")#append()参数可以将元素添加到列表末尾 print(name) name.insert(1,"zhaoliu")#在索引为1 的位置添加zhaoliu元素 print(name)
4、从列表中删除元素
name=["zhangsan","lisi","ljy"] print(name) del name[1] #删除元素 print(name) name=["zhangsan","lisi","ljy"] print(name) pop_name=name.pop(1) #pop()参数可以删除列表任意位置的元素,并让你接着使用它 print(name) print(pop_name)
如果你要从列表中删除一个元素且以后不再使用它,可以使用del函数,如果删除以后还要继续使用它可以使用pop函数。
5、根据值删除元素
name=["zhangsan","lisi","ljy"] print(name) name.remove("ljy") #删除ljy元素 print(name)
6、列表永久性排序
name=["zhangsan","lisi","ljy"] print(name) name.sort() #函数sort()永久性修改按字母排序 print(name) name.sort(reverse=True) #反着排序 print(name)
7、列表临时排序
name=["zhangsan","lisi","ljy"] print(name) print(sorted(name)) print(name)
8、倒着打印列表
name=["zhangsan","lisi","ljy"] print(name) name.reverse() #反转列表元素排序 print(name)
9、获取列表长度
name=["zhangsan","lisi","ljy"] print(len(name)) #函数len()可快速获悉列表长度
10、遍历整个列表
name=["zhangsan","lisi","ljy"] for user in name: #for循环末尾的冒号告诉python,下一行是循环的第一行 print(user)
11、创建数值列表
for name in range(1,5): #函数rang()可以生成一系列数字 print(name) number=list(range(1,6)) #list()函数嫩能够转换为列表 print(number) number=list(range(1,12,2)) #list()函数从1开始每次加2一直到数值12 print(number)
12、生成数值列表
number=[] for age in range(1,11): age2=age**2 #两个星号表示乘方运算 number.append(age2) print(number) #注意此处是否缩进
13、对数字列表执行简单的统计
number=[1,2,3,4,5,6,89] print(min(number)) print(max(number)) print(sum(number))
14、列表解析
number=[value**2 for value in range(1,4)] print(number)
15、使用列表中的一部分
name=["zhangsn","wer","werw","er","wer"] print(name[2:4]) #输出第二到第四个元素 print(name[:4]) #输出第一个到第四个元素 print(name[1:]) #输出第二个到最后一个元素 print(name[-3:])# 输出最后三个元素
16、遍历切片
name=["zhangsn","wer","werw","er","wer","q2342"] print("these people:") for user in name[0:3]: print(user)
17、复制列表
name=["zhangsn","wer","werw","er","wer","q2342"] user=name[:] print(name) print(user) name.append("name") user.append("user") print(name) print(user)
18、定义一个元祖
不可变的列表称为元祖
元祖看起来犹如列表,但使用圆括号而不是方括号来标识。
name=(1,2,3) print(name) print(name[0])