字典在每循环循环中都会被覆盖 [英] Dictionary keeps getting overwritten in each iteration of for-loop
问题描述
import random
o=['§','±','!','@','#','$','%','^','&','*','(',')','','_','=','+','/','[']
q=['1','2','3','4','5','6','7','8','9','0']
for i in top_25:
wordDic ={i: random.choice(o)+random.choice(q)}
print(wordDic)
(top_25是一组单词,random.choice从各个数组中随机选择字符)。当for循环迭代时,wordDic会不断更新和重写本身 - 是否有一种方法可以将wordDic的新值添加到字典中,因此它会在一个字典中打印出所有这些值?
(top_25 is an array of words, and the random.choice randomly selects characters from the respective arrays). As the for loop iterates, the wordDic keeps updating and overwriting itself-is there a way to add the new values of the wordDic into the dictionary, so it prints out all of them in one dictionary?
推荐答案
因为您正在循环中定义字典。
Because you are defining the dictionary inside the loop.
这意味着您正在重新绘制/覆盖在循环的每次迭代期间的字典(来自:@MT的评论)
Which means that you are redifining/overwriting the dictionary during each iteration of the loop ( Comment from: @M.T )
在循环之外定义它以使其正常工作。
Define it outside the loop to get it work.
word_dic = {}
for i in top_25:
word_dic[i] = random.choice(o)+random.choice(q)
print(word_dic)
这篇关于字典在每循环循环中都会被覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!