嘿,我正在尝试将这两个列表合并为一个字典。但是,在第二个for循环中,它只会继续执行该操作,而不会返回第一个。任何帮助将非常感激。谢谢!
import random
chores = ['dishes','bathroom','vacuum','walk dog']
assign = {}
emails = ['a','b','c','d']
x=0
while x < 4:
for i in chores:
randomChore = random.choice(chores)
chores.remove(randomChore)
for key in emails:
assign[key] = randomChore
x = x + 1
答案 0 :(得分:1)
您只需要random.shuffle
,它的工作原理就是这样
import random
chores = ['dishes','bathroom','vacuum','walk dog']
assign = {}
emails = ['a','b','c','d']
random.shuffle(chores)
res = {key:val for key,val in zip(emails,chores)}
答案 1 :(得分:0)
在您的代码中,for key in emails:
部分需要删除。它会选择随机的杂项然后循环浏览,添加电子邮件而不会选择其他随机的杂项。
这是工作代码。
import random
chores = ['dishes','bathroom','vacuum','walk dog']
assign = {}
emails = ['a','b','c','d']
x = 0
for i in range(0, len(chores)):
randomChore = random.choice(chores)
chores.remove(randomChore)
assign[emails[x]] = randomChore
x = x + 1
print(assign)
答案 2 :(得分:0)
这里,您不需要无用的内部,而无需循环遍历遍历键:
import random
chores = ['dishes','bathroom','vacuum','walk dog']
assign = {}
emails = ['a','b','c','d']
for i in emails:
randomChore = random.choice(chores)
chores.remove(randomChore)
assign[i] = randomChore
print(assign)