列表基础
列表由一系列按特定顺序排列的元素组成。在Python中,用方括号[]表示列表,用逗号分隔其中的元素。
一.访问列表元素
列表是有序集合,访问列表的任何元素,只需将该元素的位置或索引告诉Python即可。
索引从0开始而不是从1开始。
python为访问最后一个元素提供了一种特殊的语法。通常将索引指定为-1,可使Python返回最后一个元素。
这种约定也适用于其他负数索引,-2返回倒数第二个列表元素。
bicycles=['trek','cannondale','redline','specialized']
print(bicycles[1])
print(bicycles[3])
print(bicycles[-1])
message='My first bicycle was a ' + bicycles[0].title() + '.'
print(message)
cannondale
specialized
specialized
My first bicycle was a Trek.
二.修改列表元素
要修改列表元素,可指定列表名和要修改的元素索引,再指定该元素的新值。
motorcycles=['honda','yamaha','suzuki']
motorcycles[0]='ducati'
print(motorcycles)
['ducati', 'yamaha', 'suzuki']
三.在列表中添加元素
append()在列表末尾添加元素。这种方法让动态的创建列表易如反掌。可以先创建空列表,再使用一系列的append()语句添加元素。
insert()可在列表的任何位置添加新元素,需要指定新元素的索引和值。
motorcycles=['honda','yamaha','suzuki']
motorcycles.append('ducati')
print(motorcycles)
['honda', 'yamaha', 'suzuki', 'ducati']
motorcycles=['honda','yamaha','suzuki']
motorcycles.insert(0,'ducati')
print(motorcycles)
['ducati', 'honda', 'yamaha', 'suzuki']
四.从列表中删除元素
知道要删除的元素在列表中的位置,可使用del语句。
del可删除任何位置处的列表元素,条件是知道索引。
motorcycles=['honda','yamaha','suzuki']
del motorcycles[0]
print(motorcycles)
['yamaha', 'suzuki']
使用pop()方法
方法pop()可删除列表末尾的元素,并让你能够接着使用它。术语弹出(pop)源自这样的类比:列表就像一个栈,而删除列表末尾的元素相当于弹出栈顶元素。
motorcycles=['honda','yamaha','suzuki']
popped_motorcycle=motorcycles.pop()
print(motorcycles)
print(popped_motorcycle)
['honda', 'yamaha']
suzuki
pop()可以弹出列表中任何位置的元素,只要在括号中指定要删除元素的索引即可。
motorcycles=['honda','yamaha','suzuki']
popped_motorcycle=motorcycles.pop(1)
print(motorcycles)
print(popped_motorcycle)
['honda', 'suzuki']
yamaha
如果要从列表中删除一个元素,且不再以任何方式使用它,就使用del语句,如果在删除元素后还能继续使用它,就使用方法pop()。
根据值删除元素remove()
使用remove()删除元素时,也可以接着使用它的值。
motorcycles=['honda','yamaha','suzuki','ducati']
too_expensive='ducati'
motorcycles.remove(too_expensive)
print(motorcycles)
print('\nA ' + too_expensive.title() + ' is too expensive for me.')
['honda', 'yamaha', 'suzuki']
A Ducati is too expensive for me.
方法remove()只删除第一个指定的值。
如果要删除的值可能在列表中出现多次,就要使用循环来判断是否删除了所有这样的值。
五.组织列表
1.使用方法sort()对列表进行永久性排序
cars=['bmw','audi','toyota','subaru']
cars.sort()
print(cars)
['audi', 'bmw', 'subaru', 'toyota']
方法sort()以元素字母顺序排序,永久的修改了列表元素的排列顺序。
若要以与字母顺序相反的顺序排列列表元素,只要向sort()方法传递参数reverse=True
cars=['bmw','audi','toyota','subaru']
cars.sort(reverse=True)
print(cars)
['toyota', 'subaru', 'bmw', 'audi']
2.使用函数sorted()对列表进行临时排序
sorted()用于保留列表元素原来的排列顺序,同时以特定的顺序呈现它们。
cars=['bmw','audi','toyota','subaru']
print('Here is the sorted list:')
print(sorted(cars,reverse=True))
print('Here is the original list:')
print(cars)
Here is the sorted list:
['toyota', 'subaru', 'bmw', 'audi']
Here is the original list:
['bmw', 'audi', 'toyota', 'subaru']
3.倒着打印列表reverse()
方法reverse()可以永久性地修改列表元素的排列顺序,但可随时恢复到原来的排列顺序,只要对列表再次调用reverse()即可。
cars=['bmw','audi','toyota','subaru']
cars.reverse()
print(cars)
['subaru', 'toyota', 'audi', 'bmw']
reverse()只是倒着打印输出,并不对原列表进行排序。
4.确定列表的长度len()
cars=['bmw','audi','toyota','subaru']
print(len(cars))
4
六.操作列表
1.遍历整个列表
对列表中的每个元素都执行相同的操作时,可以用Python执行去处理这些问题。
编写for循环时,对于用于存储列表中的每个值的临时变量,可以指定任何名称。
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')
print("Thank you,everyone. That was a great magic show!")
Alice, that was a great trick!
I can't wait to see your next trick, Alice.
David, that was a great trick!
I can't wait to see your next trick, David.
Carolina, that was a great trick!
I can't wait to see your next trick, Carolina.
Thank you,everyone. That was a great magic show!
2.创建数值列表
(1)使用函数range()
函数range()让你从指定的第一个值开始数,并在到达你指定的第二个值后停止,输出不包含第二个值。
for value in range(1,6):
print(value)
numbers=list(range(1,6))
print(numbers)
1
2
3
4
5
[1, 2, 3, 4, 5]
函数list()可以直接将range()的结果转化为列表。
range()的第三个参数用于指定步长。
even_numbers=list(range(2,11,2))
print(even_numbers)
[2, 4, 6, 8, 10]
函数range()从2开始数,然后不断加2,指导达到或超过终值11。
(2)对数字列表执行简单的统计计算
min()、max()、sum()分别用于找出数字列表的最小值,最大值和总和。
digits=[1,2,3,4,5,6,7,8,9,0]
print(min(digits))
print(max(digits))
print(sum(digits))
0
9
45
3.列表解析
列表解析将for循环和创建新元素的代码合成一行,并自动添加新元素。
squares=[value**2 for value in range(1,11)]
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
首先指定一个描述性的列表名,
然后指定一个左方括号,
并定义一个表达式,用于生成存储到列表的值,
最后编写for循环,用于给表达式提供值,再加上右方括号。
七.使用列表的一部分
1.切片
创建切片要指定使用的第一个元素和最后一个元素的索引,在到达指定的第二个索引前面的元素后停止。
没有指定第一个索引,Python将自动从列表开头开始;
没有指定第二个索引,切片将终止于列表末尾。
负数索引返回离列表末尾相应距离的元素,因此可以输出列表末尾的所有元素。
players=['charles','martina','michael','florence','eli']
print(players[1:4])
print(players[2:])
print(players[:3])
print(players[-3:])
['martina', 'michael', 'florence']
['michael', 'florence', 'eli']
['charles', 'martina', 'michael']
['michael', 'florence', 'eli']
遍历切片
遍历列表的部分元素,可在for循环中使用切片。
players=['charles','martina','michael','florence','eli']
print('Here are the first three players on my team:')
for player in players[:3]:
print(player.title())
2.复制列表
复制列表的方法是同时省略起始索引和终止索引([:])。
my_foods=['pizza','falafel','carrot cake']
friend_foods=my_foods[:]
print(my_foods,'\n',friend_foods)
不使用切片的情况下复制列表,行不通
my_foods=['pizza','falafel','carrot cake']
friend_foods=my_foods
my_foods.append('cannoli')
friend_foods.append('ice cream')
print(my_foods)
print(friend_foods)
['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']
['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']
这里将my_foods赋给friend_foods,而不是将my_foods的副本存储到friend_foods中,因此这两个变量都指向同一个列表。
六.元组
元组使用圆括号来标识,Python不能给元组的元素赋值,元组不可变。
虽然不能修改元素的元素,但是可以给存储元组的变量赋值。
dimensions=(200,50)
dimensions[0]=30
Traceback (most recent call last):
File "c:/work/dailyexe/exe_0623_1.py", line 102, in <module>
dimensions[0]=30
TypeError: 'tuple' object does not support item assignment
dimensions=(200,50)
for dimension in dimensions:
print(dimension)
dimensions=(100,300)
for dimension in dimensions:
print(dimension)
200
50
100
300