Python编程:从入门到实践
1 操作列表 (第四章)
1.1 遍历列表
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!
1.2 创建数值列表
1.2.1 range()
range(初始数值,结束数值,步长)
略
1.2.2 其他函数
max(数值列表)
min(数值列表)
sum(数值列表)
略
1.2.3 列表解析(important)
列表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.3 使用列表的一部分
1.3.1 列表切片
列表名[初始索引(不写则从头开始):结束索引(不写则到最后):步长(不写则为1)]
类比range()
略
1.3.2 复制列表
采用全切片列表名[:]
以下是代码:
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’]
1.4 元组
1.4.1 遍历
略
1.4.2 更改
对元组重新赋值
略
1.5 设置代码格式
大家一般遵循PEP 8
的格式,这是一个有良好作风的程序员的好习惯。
详细格式请点击这里
2 if 语句 (第五章)
2.1 条件测试
2.1.1 检查特定值是否包含在列表中
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.
2.2 用 if 语句处理列表
2.2.1 确定列表不是空的
以下是代码:
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?
3 字典 (第六章)
3.1 遍历字典
字典名.items()
和 字典名.keys()
和 字典名.values()
都会返回为list(列表)
3.1.1 遍历字典的键值对
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
3.1.2 遍历字典的键
for 键 in 字典名.keys()
或 for 键 in 字典名
代码及效果略
3.1.3 遍历字典的值
for 值 in 字典名.values()
代码及效果略
去除重复项的方法:将列表转化成集合 set(列表)
详略
3.2 字典嵌套
3.2.1 列表里的字典
多个结构相同的字典
3.2.2 字典里的列表
一个键关联到多个值
3.2.3 字典里的字典
代码很复杂