我正在尝试为此嵌套字典执行以下两项操作:
如果一只鸟具有攻击性,请打印一条字符串,建议我们使用此打印语句中的“动作”列表“遮住头部”
如果一只鸟濒临灭绝,请打印一个字符串,建议我们“后退”,并使用此打印语句中的操作列表
这是我到目前为止所拥有的。非常感谢您的帮助!:
rarebirds = {
'Gold-crested Toucan': {
'Height (m)': 1.1,
'Weight (kg)': 35,
'Color': 'Gold',
'Endangered': True,
'Aggressive': True},
'Pearlescent Kingfisher': {
'Height (m)': 0.25,
'Weight (kg)': 0.5,
'Color': 'White',
'Endangered': False,
'Aggressive': False},
'Four-metre Hummingbird': {
'Height (m)': 0.6,
'Weight (kg)': 0.5,
'Color': 'Blue',
'Endangered': True,
'Aggressive': False},
'Giant Eagle': {
'Height (m)': 1.5,
'Weight (kg)': 52,
'Color': 'Black and White',
'Endangered': True,
'Aggressive': True},
'Ancient Vulture': {
'Height (m)': 2.1,
'Weight (kg)': 70,
'Color': 'Brown',
'Endangered': False,
'Aggressive': False}
}
actions = ['Back Away', 'Cover our Heads', 'Take a Photograph']
for key, value in rarebirds.items():
for value in value:
if value == 'Aggressive' and True:
print(key, ":", actions[1])
return
for key, value in rarebirds.items():
for value in value:
if value == 'Endangered' and True:
print(key, ":", actions[0])
return
您将得到以下答案:
而且
上面的代码在您的代码中是错误的。 你可以试试看,而不是这个
另一种方法是将名称和操作序列构建为元组
这里的目的是展示生成器的使用,这有助于避免构建额外的数据结构(请注意,甚至每个元组都可以被生成器替换,具体取决于它的使用)
例如,假设您只能拍摄中性物种的照片:
产生
确定的问题:
return
语句不是必需的李>if value == 'Aggressive' and True:
-对于将Aggressive
作为其值之一的所有键,无论它是True
还是False
,此条件都为真李>因为
rarebirds
是一个dict
,所以我们不想遍历value
。它可以简单地写为对于输出
相关问题 更多 >
编程相关推荐