for 元素 in 列表
以下是代码:
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician.title() + ", that was a great trick!")
以下是运行效果:
Alice, that was a great trick!
David, that was a great trick!
Carolina, that was a great trick!
range(初始数值,结束数值,步长)
略
max(数值列表)
min(数值列表)
sum(数值列表)
略
列表2 = [元素2 for 元素1 in 列表1]
注:元素2 一般用元素1计算得出
以下是代码:
squares = [i**2 for i in range(1,11)]
print(squares)
以下是运行效果:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
列表名[初始索引(不写则从头开始):结束索引(不写则到最后):步长(不写则为1)]
类比range()
略
采用全切片列表名[:]
以下是代码:
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are:")
print(my_foods)
print("My friend's favorite foods are:")
print(friend_foods)
以下是运行效果:
My favorite foods are:
[‘pizza’, ‘falafel’, ‘carrot cake’, ‘cannoli’]
My friend’s favorite foods are:
[‘pizza’, ‘falafel’, ‘carrot cake’, ‘ice cream’]
以下是代码(错误示例):
my_foods = ['pizza', 'falafel', 'carrot cake']
#这行不通
friend_foods = my_foodsmy_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are:")
print(my_foods)
print("My friend's favorite foods are:")
print(friend_foods)
以下是运行效果(错误示例):
My favorite foods are:
[‘pizza’, ‘falafel’, ‘carrot cake’, ‘cannoli’, ‘ice cream’]
My friend’s favorite foods are:
[‘pizza’, ‘falafel’, ‘carrot cake’, ‘cannoli’, ‘ice cream’]
略
对元组重新赋值
略
大家一般遵循PEP 8
的格式,这是一个有良好作风的程序员的好习惯。
详细格式请点击这里
if 元素 in 列表:
以下是代码:
banned_users = ['andrew', 'carolina', 'david']
user = 'marie'
if user not in banned_users:
print(user.title() + ", you can post a response if you wish.")
以下是运行效果:
Marie, you can post a response if you wish.
以下是代码:
requested_toppings = []
if requested_toppings:
for requested_topping in requested_toppings:
print("Adding " + requested_topping + ".")
print("Finished making your pizza!")
else:
print("Are you sure you want a plain pizza?")
以下是运行效果:
Are you sure you want a plain pizza?
字典名.items()
和 字典名.keys()
和 字典名.values()
都会返回为list(列表)
for 键,值 in 字典名.items()
以下是代码:
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for key, value in user_0.items():
print("Key: " + key)
print("Value: " + value)
以下是运行效果:
Key: username
Value: efermi
Key: first
Value: enrico
Key: first
Value: enrico
for 键 in 字典名.keys()
或 for 键 in 字典名
代码及效果略
for 值 in 字典名.values()
代码及效果略
去除重复项的方法:将列表转化成集合 set(列表)
详略
多个结构相同的字典
一个键关联到多个值
代码很复杂