1.列表通常包含多个元素,通常给列表指定一个表示复数的名称(如 letters 、 digits 或 names )
2.Python为访问最后一个列表元素提供了一种特殊语法。通过将索引指定为 -1 ,可让Python返回最后一个列表元素。
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[-1])
结果:specialized
3.在列表中添加新元素时,最简单的方式是将元素附加到列表末尾。 .append()
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles.append('ducati')
print(motorcycles)
4.使用方法 insert() 可在列表的任何位置添加新元素。
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.insert(0, 'ducati')
print(motorcycles)
插到位置0,结果:['ducati', 'honda', 'yamaha', 'suzuki']
5.删除表元素:使用 del 可删除任何位置处的列表元素,条件是知道其索引。
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
del motorcycles[0]
print(motorcycles)
结果:['honda', 'yamaha', 'suzuki']
['yamaha', 'suzuki']
6.可以使用 pop() 来删除列表中任何位置的元素,只需在括号中指定要删除的元素的索引即可。
7.如果你只知道要删除的元素的值,可使方法 用方法 remove() ,remove() 只删除第一个指定的值。
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcyclesmotorcycles.remove('ducati')
print(motorcycles)
8.对列表元素进行组织(位置变换)sort函数是永久性改变的,sorted函数并没有实际改变位置,这是区别。
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort() # 按照字母顺序排序
print(cars)
cars.sort(reverse=True) # 按照反向字母排序
print(cars)
9.要反转列表元素的排列顺序,可使用方法 reverse()按照原有顺序翻转,永久性改变,再用一次翻转回来。
10.使用函数 len() 可快速获悉列表的长度。
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(len(cars))
结果:4
11.对列表进行for循环操作(别忘了循环的:),缩进代码就进入for循环内,magician是存储列表内元素的一个变量。
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician.title() + ", that was a great trick!")
print("I can't wait to see your next trick, " + magician.title() + ".\n")
12.打印数字 range()函数
for value in range(1,5):
print(value)
结果:1234 注意只打印到4
13.range(10) # 从 0 开始到 10
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
range(1, 11) # 从 1 开始到 11
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
range(0, 30, 5) # 步长为 5
[0, 5, 10, 15, 20, 25]
range(0, 10, 3) # 步长为 3
[0, 3, 6, 9]
range(0, -10, -1) # 负数
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
squares = []
for value in range(1,11):
square = value**2
squares.append(square)
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
13.简单统计
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
min(digits)
max(digits)
sum(digits)
14.少个:
squares = [value**2 for value in range(1,11)]
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
15.列表切片
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3])
print(players[1:4])
print(players[:4])
print(players[2:])
print(players[-3:])#打印最后三个
16.遍历切片
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print("Here are the first three players on my team:")
for player in players[:3]:
print(player.title())
结果:Here are the first three players on my team:
Charles
Martina
Michael
17.列表复制
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]#这样使用切片复制完毕后,是完整的两个独立列表
friend_foods = my_foods#这样地址映射还是一个,改一个另一个也会改变
18.元组
dimensions = (200, 50)
元组不同于列表,是用()定义的,元组的值是不可以更改的,但是可以重新定义覆盖。
dimensions = (200, 50)
dimensions = (400, 100)
元组使用for循环遍历
for dimension in dimensions:
print(dimension)