python-列表
一、列表
1、访问列表元素
bicycles=['trek','cannondale','redline']
print(bicycles[0])
title()方法:输出字符串首字母大写
索引从0而不是1开始
2、增删改
增加可用append()方法和insert()方法
删除用del语句,pop()方法,remove()方法
3、列表排序
3.1、使用方法sort()对列表进行永久性排序
3.2、使用函数sorted()对列表进行临时排序
3.3、倒着打印列表用reverse()方法(永久性修改,再次reverse将还原)
3.4、确定列表长度用函数len()
4、操作列表
4.1、遍历整个列表用for循环
4.2、创建数字列表
4.2.1使用函数range()创建数字列表
numbers=list(range(1,6))
print (numbers)
结果:[1,2,3,4,5]
4.2.2创建平方
squares=[]
for value in range(1,11):
squares.append(value**2)
print(squares)
4.2.3列表解析
squares=[value**2 for value in range(1,11)]
print(squares)
4.3、使用列表的一部分
4.3.1切片
players=['charles','marry','linda','eli']
print(players[0:2])
输出前两名队员
如果没有指定第一个索引,python将自动从列表开头开始:print(players[:2])
让切片终止于列表末尾,print(players[2:]) 负数索引返回离列表末尾相应距离的元素,输出名单上最后两位队员print(players[-2:])
4.3.2复制列表
my_foods=['pizza','falafel','carrot cake']
friends_foods=my_foods[:]
4.4、元祖
4.4.1定义元祖
dimensions=(200,50)
print(dimensions[0])
4.4.2修改元祖变量
元祖不能修改元素,但可以给存储元祖的变量复制,因此,可通过重新定义整个元祖来实现修改