三、列表简介
列表由一系列按特定顺序排列的元素组成,列表用方括号([ ])表示。
>>> bicycles=['trek','cannondale','redline','specialized'];\
print(bicycles)
['trek', 'cannondale', 'redline', 'specialized']
(1)访问列表元素:列表名[n]
索引从0开始;-n表示倒数第n个元素
>>> bicycles=['trek','cannondale','redline','specialized'];\
print(bicycles[1].title());\
print(bicycles[-1])
Cannondale
specialized
>>> bicycles=['trek','cannondale','redline','specialized'];\
message="My first bicycle was a "+bicycles[0].title()+".";\
print(message)
My first bicycle was a Trek.
(2)修改、添加和删除元素:
修改:直接赋值
>>> bicycles=['trek','cannondale','redline','specialized'];\
bicycles[2]='ducati';\
print(bicycles)
['trek', 'cannondale', 'ducati', 'specialized']
添加:在末尾添加:append(要添加的元素)
>>> bicycles=['trek','cannondale','redline','specialized'];\
bicycles.append('ducati');\
print(bicycles)
['trek', 'cannondale', 'redline', 'specialized', 'ducati']
在列表插入:insert(n,要添加的元素)
>>> bicycles=['trek','cannondale','redline','specialized'];\
bicycles.insert(1,'ducati');\
print(bicycles)
['trek', 'ducati', 'cannondale', 'redline', 'specialized']
删除:del 列表名[n],可删除任意元素,删除后就无法访问该元素;
>>> bicycles=['trek','cannondale','redline','specialized'];\
del bicycles[0];\
print(bicycles)
['cannondale', 'redline', 'specialized']
pop(),可删除任意元素,默认堆栈删除,删除后可以访问该元素;
>>> bicycles=['trek','cannondale','redline','specialized'];\
last_owned=bicycles.pop();\
print(bicycles);\
print(last_owned)
['trek', 'cannondale', 'redline']
specialized
>>> bicycles=['trek','cannondale','redline','specialized'];\
second_owned=bicycles.pop(1);\
print('The second bicycle I owned was a '+second_owned.title()+'.')
The second bicycle I owned was a Cannondale.
remove(),根据值删除元素,只删除第一个符合要求的值(可以使用循环删除所有值),可以访问。
>>> bicycles=['trek','cannondale','redline','specialized'];\
too_expensive='specialized';\
bicycles.remove(too_expensive);\
print(bicycles);\
print('\nA '+too_expensive.title()+' is too expensive for me.')
输出结果:
['trek', 'cannondale', 'redline']
A Specialized is too expensive for me.
(3)组织列表(排序、长度)
永久性排序:sort(),按字母排序,可正可反,无法恢复;
>>> bicycles=['trek','cannondale','redline','specialized'];\
bicycles.sort();\
print(bicycles)
['cannondale', 'redline', 'specialized', 'trek']
按字母反向排序:reverse=True,无法恢复
>>> bicycles=['trek','cannondale','redline','specialized'];\
bicycles.sort(reverse=True);\
print(bicycles)
['trek', 'specialized', 'redline', 'cannondale']
>>> numbers=[2,6,0,4,5,9,8,7];\
numbers.sort(reverse=True);\
print(numbers)
[9, 8, 7, 6, 5, 4, 2, 0]
临时排序:sorted(),可正可反,不改变原始排序;
>>> bicycles=['trek','cannondale','redline','specialized'];\
print (sorted(bicycles));\
print(bicycles)#原始顺序没有改变
['cannondale', 'redline', 'specialized', 'trek']
['trek', 'cannondale', 'redline', 'specialized']
倒着打印:reverse(),永久改变,但可再次使用reverse()来恢复;
>>> bicycles=['trek','cannondale','redline','specialized'];\
bicycles1=bicycles.reverse();\
print(bicycles);\
print(bicycles1)
['specialized', 'redline', 'cannondale', 'trek']
None
注:不能赋值
确定列表长度:len()
>>> bicycles=['trek','cannondale','redline','specialized'];
>>> len(bicycles)
4
四、操作列表
1.遍历整个列表
for循环
magicians=['alice','david','carlina']
for person in magicians:#person可被替换成任意临时变量名
print(person)
输出结果:
alice
david
carlina
magicians=['alice','david','carlina']
for person in magicians:
print(person.title()+',that was a great trick!')#注意缩进与不缩进区别
print("I can't wait to see your next trick,"+person.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.
Carlina,that was a great trick!
I can't wait to see your next trick,Carlina.
Thank you,everyone.That was a great magic show!
注意:该缩进时必须缩进,不该缩进时不要缩进;
不要遗漏冒号。
2.创建数字列表
(1)函数range()
range(起始值,终值,步长),默认初值为0,默认步长为1.
for value in range(1,5):
print(value)
输出结果:
1
2
3
4
注:不是1 2 3 4 5
(2)使用range()创建数字列表:list()
even_numbers=list(range(0,11,2))
print(even_numbers)
输出结果:
[0, 2, 4, 6, 8, 10]
平方数字列表
squares=[] #创建空列表
for value in range(1,11):
square=value**2
squares.append(square)#在列表后加入新的平方值
print(squares)
或
squares=[] #创建空列表
for value in range(1,11):
squares.append(value**2)#在列表后加入新的平方值
print(squares)
输出结果:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
(3)对数字列表进行简单的统计计算:min(),max(),sum()等
>>> digits=[1,2,3,4,5,6,7,8,9,0]
>>> min(digits)
0
>>> max(digits)
9
>>> sum(digits)
45
(4)列表解析:将for循环和创建新元素代码合并成一行,并自动附加新元素。
squares=[value**2 for value in range(1,11)]
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
3.使用列表的一部分
(1)切片[起始元素:终止元素+1];可反向索引(-n)
players=['charles','martina','michael','florence','eli']
print(players[1:3])
print(players[:4])
print(players[-4:-1])
print(players[-3:])
输出结果:
['martina', 'michael']
['charles', 'martina', 'michael', 'florence']
['martina', 'michael', 'florence']
['michael', 'florence', 'eli']
(2)遍历切片: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())
输出结果:
Here are the first three players on my team:
Charles
Martina
Michael
(3)复制列表:同时省略起始索引和终止索引[:]
my_foods=['pizza','apple','carrot cake']
friend_foods=my_foods[:]
print('My favorite foods are:')
print(my_foods)
print("My frieds's favorite foods are:")
print(friend_foods)
#附加食物后各自不同
my_foods.append('hot dog')
friend_foods.append('ice cream')
print('\nMy favorite foods are:')
print(my_foods)
print("My frieds's favorite foods are:")
print(friend_foods)
输出结果:
My favorite foods are:
['pizza', 'apple', 'carrot cake']
My frieds's favorite foods are:
['pizza', 'apple', 'carrot cake']
My favorite foods are:
['pizza', 'apple', 'carrot cake', 'hot dog']
My frieds's favorite foods are:
['pizza', 'apple', 'carrot cake', 'ice cream']
若无[:]
my_foods=['pizza','apple','carrot cake']
friend_foods=my_foods
print('My favorite foods are:')
print(my_foods)
print("My frieds's favorite foods are:")
print(friend_foods)
#附加食物后相同
my_foods.append('hot dog')
friend_foods.append('ice cream')
print('\nMy favorite foods are:')
print(my_foods)
print("My frieds's favorite foods are:")
print(friend_foods)
输出结果:
My favorite foods are:
['pizza', 'apple', 'carrot cake']
My frieds's favorite foods are:
['pizza', 'apple', 'carrot cake']
My favorite foods are:
['pizza', 'apple', 'carrot cake', 'hot dog', 'ice cream']
My frieds's favorite foods are:
['pizza', 'apple', 'carrot cake', 'hot dog', 'ice cream']
4.元组
不可变的列表称为元组。
(1)定义元组:用圆括号()表示
dimensions=(200,50)
print(dimensions[0])
print(dimensions[-1])
#dimensions[0]=250
#上句错误,不能给元组的元素赋值
输出结果:
200
50
(2)遍历元组中所有值:for循环
dimensions=(200,50)
for dimension in dimensions:
print(dimension)
输出结果:
200
50
(3)修改元组变量:可以给存储元组的变量赋值
dimensions=(200,50)
print('Original dimensions:')
for dimension in dimensions:
print(dimension)
#修改
dimensions=('danny','jenny')
print('\nModified dimensions:')
for dimension in dimensions:
print(dimension)
输出结果:
Original dimensions:
200
50
Modified dimensions:
danny
jenny
附:
代码格式:缩进:每级4个空格;
行长:不超过80字符
空行:适中
参考文献:袁国忠,Python编程:从入门到实践