我以前从未在Python for循环中遇到过这种情况。
我有Names (key)
和Regions (value)
的字典。我想将每个名称与其他两个名称匹配。匹配的名称不能是它们自己,并且反转元素不是有效的匹配(1,2) = (2,1)
。不过,我不希望来自同一地区的人们匹配在一起(除非不可能)。
dict = {
"Tom":"Canada",
"Jerry":"USA",
"Peter":"USA",
"Pan":"Canada",
"Edgar":"France"
}
所需的可能输出:
[('Tom','Jerry'),('Tom','Peter'),('Jerry','Pan'),('Pan','Peter'),('Edgar','Peter'),('Edgar','Jerry')]
每个人出现两次,但为了让Edgar与来自不同地区的姓名进行2次匹配,Jerry和Peter出现的次数更多(应在此处随机选择Jerry和Peter)
Count: Tom: 2, Jerry: 3, Peter: 3, Pan: 2, Edgar: 2
我的方法是将名称转换为列表,将它们混洗,然后在自定义函数中使用zip创建元组对。功能完成后。我使用for
来检查来自同一区域的配对,如果存在相同的配对区域,则重新运行自定义函数。由于某些原因,当我打印结果时,我仍然看到相同区域之间的配对。我在这里想念什么?
import random
names=list(dict.keys())
def pairing(x):
random.shuffle(x)
#each person is tupled twice, once with the neighbor on each side
pairs = list(zip(x, x[1:]+x[:1]))
return pairs
pairs=pairing(names) #assigns variable from function to 'pairs'
for matchup in pairs:
if dict[matchup[0]]==dict[matchup[1]]:
break
pairing(names)
pairs=pairing(names)
for matchup in pairs:
print(matchup[0] ,dict[matchup[0]] , matchup[1] , dict[matchup[1]])
仅查看它,for循环中的某些内容显然已损坏,请帮忙!
我在for循环中尝试使用while
而不是if
,但是没有用。
答案 0 :(得分:0)
from itertools import combinations
import pandas as pd
import random
dict={'your dictionary'}
#create function to pair names together
def pairing(x):
random.shuffle(x)
#each person is tupled twice, once with the neighbor on each side
pairs = list(zip(x, x[1:]+x[:1]))
for matchup in pairs:
if dict[matchup[0]]==dict[matchup[1]]: #if someone's gym matches their opponent's gym in dictionary, re-run this function
return pairing(x)
return pairs
pairs=pairing(names)
for matchup in pairs:
print(matchup[0] ,dict[matchup[0]] , matchup[1] , dict[matchup[1]])
诀窍是在自定义函数内return pairing(x)
。如果元组中的任何元素在字典中共享相同的值,则将返回新的配对。如果在if statement
中,先进入pairing(x)
,然后再进入return pair
,它将返回包含重复项的原始元组列表。