Python编程 从入门到实践 第4章 操作列表

1 for-in 循环

magicians = ['alice','david','carolina']
for magician in magicians:
	print(magician)

2 用range()生成一系列数字

for value in range(1,5):
	print(value) 

#输出 1 2 3 4

3 用range()和list()生成数字列表,range()可以设置步长

b = list(range(1,6))
print(b)   # b为列表,[1,2,3,4,5]

even_number = list(range(2,11,2))
print(even_number)

4 数字列表计算

>>> digits = [1,2,3,4,5,6,7,8,9,0]
>>> min(digits)
0
>>> max(digits)
9
>>> sum(digits)
45

5 列表解析

>>> squares = [value**2 for value in range(1,11)]
>>> print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

6 切片,范围是左闭右开

players = ['charles','martina','florence','eli']
print(players[0:3])   # ['charles', 'martina', 'florence']
print(players[-3:])   # ['martina','florence','eli']

7 列表赋值是引用赋值,任何一个改变是两个都改变;切片赋值是参数赋值,任何一个改变都不会影响另外一个

>>> my_foods = ['pizza','falafel','carrot cake']
>>> friend_foods = my_foods   # 引用赋值
>>> my_foods
['pizza', 'falafel', 'carrot cake']
>>> friend_foods
['pizza', 'falafel', 'carrot cake']
>>> friend_foods.append('kfc')
>>> friend_foods
['pizza', 'falafel', 'carrot cake', 'kfc']
>>> my_foods
['pizza', 'falafel', 'carrot cake', 'kfc']
>>> friend_foods = my_foods[:]   # 参数赋值
>>> friend_foods
['pizza', 'falafel', 'carrot cake', 'kfc']
>>> friend_foods.append('kfc2')
>>> my_foods
['pizza', 'falafel', 'carrot cake', 'kfc']
>>> friend_foods
['pizza', 'falafel', 'carrot cake', 'kfc', 'kfc2']

元组是不可变的列表,用括号 () 表示 

>>> dimensions = (200,500)
>>> print(dimensions[0])
200
>>> print(dimensions[1])
500
>>> dimensions[0] = 12   # 元组不可修改
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

9 虽然不能修改元组的元素,但是可以给元组的变量重新赋值

>>> a = (1,2)
>>> a = (3,4)
>>> a
(3, 4)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值