Python 点滴积累(4)

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')
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值