列表(List)操作(二)
遍历整个列表 (这么命名有助于理解)
>>> players=['messi','ronaldo','xavi','pique']
>>> for player in players:
... print(player)
...
messi
ronaldo
xavi
pique
>>> for player in players:
... print(player.title()+" is a good player!")
...
Messi is a good player!
Ronaldo is a good player!
Xavi is a good player!
Pique is a good player!
>>> for a in range(1,10):
... print(a)
...
1
2
3
4
5
6
7
8
9 #注意,这里没有输出到10
>>> a=list(range(1,11))
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> squares=[]
>>> for a in range(1,11):
... b=a*a
... squares.append(b)
...
>>> squares
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> sq=[value**2 for value in range(1,11)]
>>> sq
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> k=list(range(1,11))
>>> k
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> min(k)
1
>>> max(k)
10
>>> sum(k)
55
>>> sq
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> print(sq[0:4]) #输出0,1,2,3号元素
[1, 4, 9, 16]
>>> print(sq[4:]) #让切片终止于列表末尾
[25, 36, 49, 64, 81, 100]
>>> print(sq[-3:])
[64, 81, 100]
>>> for a in sq[0:5]:
... print(a)
...
1
4
9
16
25
>>> sq
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> sq2=sq[1:5]
>>> sq2
[4, 9, 16, 25]
>>> d=(1,2,3,4,5)
>>> d
(1, 2, 3, 4, 5)
>>> d[0]
1
>>> d[0]=2 #强行修改元组的元素,解释器会报错
Traceback (most recent call last):
File "", line 1, in
TypeError: 'tuple' object does not support item assignment
>>> a=(1,2,3,4,5)
>>> list(a)
[1, 2, 3, 4, 5]
>>> a
(1, 2, 3, 4, 5) #可见a并没有真的变成list
>>> b=list(a)
>>> b
[1, 2, 3, 4, 5]
>>> b[4]=10
>>> b
[1, 2, 3, 4, 10]
>>> a=tuple(b)
>>> a
(1, 2, 3, 4, 10)