我制作了以下代码来通过字典循环键
favourite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python'
}
friends = ['sarah', 'phil']
for name in favourite_languages.keys():
print(name.title())
if name in friends:
print(" Hi " + name.title() + ", I see your favourite language is " +
favourite_languages[name].title() + "!")
产生的输出是
Jen
Sarah
Edward
Phil
Hi Phil, I see your favourite language is Python!
然而,我期待以下内容:
Jen
Sarah
Hi Sarah, I see your favourite language is C!
Edward
Phil
Hi Phil, I see your favourite language is Python!
为什么莎拉没有出现在输出中?
答案 0 :(得分:4)
解决方案是,如果条件在循环内,你只需要移动你。
favourite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python'
}
friends = ['sarah', 'phil']
for name in favourite_languages.keys():
print(name.title())
if name in friends:
print(" Hi " + name.title() + ", I see your favourite language is " +
favourite_languages[name].title() + "!")
输出:
Sarah
Hi Sarah, I see your favourite language is C!
Edward
Jen
Phil
Hi Phil, I see your favourite language is Python!
答案 1 :(得分:3)
您需要将if
语句移动到循环中。在当前状态下,它位于外部,因此只能访问name
所采用的最后一个值。
此外,我建议您将friends
存储为一组,以便快速有效地查找。
In [193]: favourite_languages = {
...: 'jen':'python',
...: 'sarah':'c',
...: 'edward':'ruby',
...: 'phil':'python'
...: }
...:
...: friends = {'sarah', 'phil'}
...: for name in favourite_languages.keys():
...: print(name.title())
...:
...: if name in friends:
...: print(" Hi " + name.title() + ", I see your favourite language is " +
...: favourite_languages[name].title() + "!")
...:
Phil
Hi Phil, I see your favourite language is Python!
Jen
Edward
Sarah
Hi Sarah, I see your favourite language is C!
集合具有恒定时间(O(1))
查找,而列表是线性(O(n))
。对于您的特定用例而言,这可能并不重要,但是设置确实会产生大量数据。
作为进一步的改进,您不需要调用dict.keys()
,因为这会创建循环键的列表以进行迭代,这有点浪费。同样的事情可以通过以下方式实现:
for name in favourite_languages:
这更简单,更有效率。
答案 2 :(得分:2)
if语句中的memory.limit(size=10000000000024)
变量在循环后设置为name
的最后一个值,而if语句只执行一次。
我认为你想缩进if语句(并打印),以便它在循环的每次迭代中执行
答案 3 :(得分:2)
您没有循环遍历name
变量。
当您的代码到达if name in friends
时,name
中存储的值为phil
。
您可以再次遍历名称(这会产生稍微不同的结果),或者为代码添加缩进。
favourite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python'
}
friends = ['sarah', 'phil']
for name in favourite_languages.keys():
print(name.title())
if name in friends:
print(" Hi " + name.title() + ", I see your favourite language is " +
favourite_languages[name].title() + "!")
答案 4 :(得分:1)
将您的def get_answer
c ? self.b = nil : b
end
块再缩进一层。
if
答案 5 :(得分:1)
您需要缩进if name in friends:
favourite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python'
}
friends = ['sarah', 'phil']
for name in favourite_languages.keys():
print(name.title())
if name in friends:
print(" Hi " + name.title() + ", I see your favourite language is " +
favourite_languages[name].title() + "!")
答案 6 :(得分:1)
只需将if
语句移至for
循环中。