Python- 如果条件为变量 True,执行分配新变量的函数直到 False

Python- If condition for a variable True, execute function assigning new variable until False

我以前从未在 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')]

每个人都出现了两次,但杰瑞和彼得出现的次数更多,以便埃德加与来自不同地区的名字进行2场比赛(这里杰瑞和彼得应该是随机选择的) Count: Tom: 2, Jerry: 3, Peter: 3, Pan: 2, Edgar: 2

我的方法是将名称转换为列表,将它们打乱顺序,然后在自定义函数中使用 zip 创建元组对。功能完成后。我使用 a 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,但没有成功。

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)在自定义函数里面。如果元组中的任何元素在字典中共享相同的值,这将 return 新配对。如果在 if statement 中,你去 pairing(x) 然后 return pair,它将 return 包含重复项的原始元组列表。