Break is not activated inside a for loop in Python [closed]

烂漫一生 提交于 2020-01-26 04:00:07

问题


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

As you can see the break is not activated. Why is that? What I should change in the code?


回答1:


You need to move the declaration of count before the for loop. It is reset to 0 at each iteration.

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

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!

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.

I recommend to spend some time studying Python, it will save you lots of debugging time.




回答2:


Initialize count outside the for loop.

count=0
 #intialize count here
for key, value in enumerate(word_index):
if count <10:
    print(f'key {key} : value: {value}')
    count = count + 1
else:
    break


来源:https://stackoverflow.com/questions/58836678/break-is-not-activated-inside-a-for-loop-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!