目录
5 if 语句
5.1 一个简单示例
5.2 条件测试
5.2.5 检查多个条件
1. 使用 and 检查多个条件
age_0 >= 21 and age_1 >= 21
(age_0 >= 21) and (age_1 >= 21)
2. 使用 or 检查多个条件
age_0 >= 21 or age_1 >= 21
5.2.6 检查特定值是否包含在列表中
要判断特定的值是否已包含在列表中,可使用关键字 in 。
requested_toppings = ['mushrooms', 'onions', 'pineapple']
'mushrooms' in requested_toppings
#输出True
'pepperoni' in requested_toppings
#输出False
5.2.7 检查特定值是否不包含在列表中
确定特定的值未包含在列表中,可使用关键字not 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.")
5.2.8 布尔表达式
布尔表达式的结果要么为 True ,要么为 False
game_active = True
can_edit = False
5.3 if 语句
5.3.4 使用多个 elif 代码块
可根据需要使用任意数量的 elif 代码块
age = 12
if age < 4:
price = 0
elif age < 18:
price = 5
elif age < 65:
price = 10
else:
price = 5
print("Your admission cost is $" + str(price) + ".")
5.3.5 省略 else 代码块
Python并不要求 if-elif 结构后面必须有 else 代码块。
age = 12
if age < 4:
price = 0
elif age < 18:
price = 5
elif age < 65:
price = 10
elif age >= 65:
price = 5
print("Your admission cost is $" + str(price) + ".")
5.3.6 测试多个条件
使用一系列简单 if 语句。
如果你只想执行一个代码块,就使用 if-elif-else 结构;如果要运行多个代码块,就使用一系列独立的 if 语句。
6 字 典
6.1 一个简单的字典
6.2 使用字典
在Python中,字典用放在花括号{ }中的一系列键—值对表示,如前面的示例所示:
alien_0 = {'color': 'green', 'points': 5}
键—值对是两个相关联的值。指定键时,Python将返回与之相关联的值。键和值之间用冒号分隔,而键—值对之间用逗号分隔。
6.2.1 访问字典中的值
alien_0 = {'color': 'green'}
print(alien_0['color'])
6.2.2 添加键—值对
字典是一种动态结构,可随时在其中添加键—值对。
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
键—值对的排列顺序与添加顺序不同。Python不关心键—值对的添加顺序,而只关心键和值之间的关联关系。(顺序随机的)
6.2.3 先创建一个空字典
alien_0 = {}
alien_0['color'] = 'green'
alien_0['points'] = 5
6.2.4 修改字典中的值
重新赋值即可
alien_0 = {'color': 'green'}
alien_0['color'] = 'yellow'
6.2.5 删除键—值对
可使用 del 语句将相应的键 — 值对彻底删除。
alien_0 = {'color': 'green', 'points': 5}
del alien_0['points']
6.2.6 由类似对象组成的字典
也可以使用字典来存储众多对象的同一种信息。缩进四个空格
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
6.3 遍历字典
6.3.1 遍历所有的键值对
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
可声明两个变量,用于存储键 — 值对中的键和值。对于这两个变量,可使用任何名称。
for key, value in user_0.items():
print("\nKey: " + key)
print("Value: " + value)
6.3.2 遍历字典中的所有键
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
friends = ['phil', 'sarah']
for name in favorite_languages.keys():
print(name.title())
if name in friends:
print(" Hi " + name.title() +
", I see your favorite language is " +
favorite_languages[name].title() + "!")
6.3.3 按顺序遍历字典中的所有键
要以特定的顺序返回元素,一种办法是在 for 循环中对返回的键进行排序。为此,可使用函数 sorted() 来获得按特定顺序排列的键列表的副本
for name in sorted(favorite_languages.keys()):
print(name.title() + ", thank you for taking the poll.")
6.3.4 遍历字典中的所有值
字典包含的值,可使用方法 values() ,它返回一个值列表,而不包含任何键
print("The following languages have been mentioned:")
for language in favorite_languages.values():
print(language.title())
这种做法提取字典中所有的值,而没有考虑是否重复。为剔除重复项,可使用集合(set)。
for language in set(favorite_languages.values()):
print(language.title())
6.4 嵌套
有时候,需要将一系列字典存储在列表中,或将列表作为值存储在字典中,这称为嵌套。
6.4.1 字典列表
例如,下面的代码创建一个包含三个外星人的列表:
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
print(alien)
在下面的示例中,我们使用 range() 生成了30个外星人:
# 创建一个用于存储外星人的空列表
aliens = []
# 创建30个绿色的外星人
for alien_number in range(30):
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
aliens.append(new_alien)
# 显示前五个外星人
for alien in aliens[:5]:
print(alien)
print("...")
# 显示创建了多少个外星人
print("Total number of aliens: " + str(len(aliens)))
6.4.2 在字典中存储列表
# 存储所点比萨的信息
pizza = {
'crust': 'thick',
'toppings': ['mushrooms', 'extra cheese'],
}
# 概述所点的比萨
print("You ordered a " + pizza['crust'] + "-crust pizza " +"with the following toppings:")
for topping in pizza['toppings']:
print("\t" + topping)
6.4.3 在字典中存储字典
users = {
'aeinstein': {
'first': 'albert',
'last': 'einstein',
'location': 'princeton',
},
'mcurie': {
'first': 'marie',
'last': 'curie',
'location': 'paris',
},
}
for username, user_info in users.items():
print("\nUsername: " + username)
full_name = user_info['first'] + " " + user_info['last']
location = user_info['location']
print("\tFull name: " + full_name.title())
print("\tLocation: " + location.title())