在Python的for循环中未激活Break [英] Break is not activated inside a for loop in Python
问题描述
我想从字典word_index中打印前10个键/值对,并编写了以下代码:
I want to print the first 10 key-value pairs from the dictionary word_index and I wrote this code:
for key, value in enumerate(word_index):
count = 0
if count <10:
print(f'key {key} : value: {value}')
count = count + 1
else:
break
如您所见,break
未激活.这是为什么?我应该在代码中更改什么?
As you can see the break
is not activated. Why is that? What I should change in the code?
推荐答案
您需要将count声明移至for循环之前.每次迭代都将其重置为0.
You need to move the declaration of count before the for loop. It is reset to 0 at each iteration.
作为一个旁注(我没有足够的声誉来发表评论),for循环可能没有按照您的意愿做.您将变量命名为key
和value
,这使我相信您要遍历字典的条目(键和值对).为此,您应该编写:
As a side note (I don't have enough reputation to comment) the for loop is probably not doing what you want. You named your variables key
and value
, which makes me believe that you want to iterate over the entries (key and value pairs) of the dictionary. To achieve that you should write:
for k,v in word_index.items():
// omitted
enumerate()
的作用是返回一个从0开始的索引,并且该索引在每次迭代时都会递增.因此,在您的代码中,key
实际上是一个索引,而value
是字典的键!
What enumerate()
does is to return an index that starts from 0 and it is incremented at each iteration. So the in your code, key
is actually an index and value
is the dictionary's key!
如果您实际上想遍历键并将索引与每个键相关联,则应将变量重命名为更正确的名称,例如index
和key
.
If you actually wanted to iterate over the keys and associate an index to each key, you should rename your variable to something more correct, for example index
and key
.
我建议花一些时间研究Python,它将为您节省大量调试时间.
I recommend to spend some time studying Python, it will save you lots of debugging time.
这篇关于在Python的for循环中未激活Break的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!