Python列表
1.遍历列表
for循环
>>> colors=["red","blue","white","green"]
>>> for color in colors:
... print(color)
...
red
blue
white
green
使用range()
>>> for value in range(1,6):
... print(value)
...
1
2
3
4
5
range()可以作为list()的参数,创建数字列表
>>> numbers=list(range(1,5))
>>> print(numbers)
[1, 2, 3, 4]
range()可以指定步长
>>> even_numbers=list(range(2,11,2))
>>> print(even_numbers)
[2, 4, 6, 8, 10]
2.列表切片
通过切片可以引用列表中的部分元素,如果省略其实索引,则从列表头开始;如果省略末尾索引,则从指定位置到列表末尾。
>>> colors=["red","orange","yellow","green","blue"]
>>> print(colors)
['red', 'orange', 'yellow', 'green', 'blue']
>>> colors[1:4]
['orange', 'yellow', 'green']
>>> colors[:3]
['red', 'orange', 'yellow']
>>> colors[2:]
['yellow', 'green', 'blue']
>>> colors[-2:]
['green', 'blue']
遍历切片
>>> for color in colors[1:4]:
... print(color)
...
orange
yellow
green
3.复制列表
>>> color=["red","orange","yellow","green","blue"]
>>> another_color=color[:]
>>> print(color)
['red', 'orange', 'yellow', 'green', 'blue']
>>> print(another_color)
['red', 'orange', 'yellow', 'green', 'blue']
>>> color.append("white")
>>> print(color)
['red', 'orange', 'yellow', 'green', 'blue', 'white']
>>> print(another_color)
['red', 'orange', 'yellow', 'green', 'blue']
4.元组
不可变的列表称为元组
元组使用圆括号来标识
访问元组和访问列表语法相同
>>> animals=("pig","dog","cat","sheep")
>>> animals[1]
'dog'
>>> animals[-1]
'sheep'
>>> for animal in animals:
... print(animal)
...
pig
dog
cat
sheep
元组中的元素不能修改,但是可以给存储元组的变量赋值。
>>> animals=("pig","dog")
>>> animals[0]="lion"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> print(animals)
('pig', 'dog')
>>> animals=("lion","monkey")
>>> print(animals)
('lion', 'monkey')