【发布时间】:2018-11-09 05:42:37
【问题描述】:
假设我有一个元组列表,其元素都是列表中所有可能的配对:
即
matchup=[('Mike','John'),('Mike','Mary'),('Mike','Jane'),('John','Mary'),('John','Jane'),('Mary','Jane')...]
我想减少列表,使每个人的名字出现两次,无论他们是配对中的第一个元素还是第二个元素。如果不这样做就无法创建新对,则元组元素可能会被选择两次以上。
提前致谢。
编辑: 最初在列表中,我使用 for 循环将每个人与另一个人随机配对 ala:
list=["John","Mike","Mary","Jane"]
pairing=[]
for person in list:
for i in range(2):
person2=random.sample(list(list),1)
this_match=str(person)+str(person2)
while this_match in pairing:
person2=random.sample(list(list),1)
this_match=str(person)+str(person2)
pairing.append(this_match)
这导致了同一个人的重复。我的第二次尝试是这样的:
from itertools import combinations
import pandas as pd
from collections import Counter
possible_games = combinations(list, 2)
games = list(possible_games)
dupe_check=Counter(games)
print(dupe_check)
print (games, len(games))
但是,我不能将每个元组的元素减少到尽可能接近两倍。
一个可能的输出可能如下所示:
[('Mike','John'),('Mike','Mary'),('John','Mary'),("Mary","Jane"),("Jane","Mike")]
约翰出现了两次。简出现了两次。为了让简出现两次,迈克出现了三次。 Mary 出现了 3 次,Jane 出现了 2 次。
【问题讨论】:
-
您尝试了什么,还添加了输出的外观,应该更清晰。
-
在你可能的输出中,Mike 和 Mary 重复了 3 次,为什么
-
因为必须有人与 Jane 配对才能重复两次,所以随机选择了 Mike。或者,约翰可能被选中,因为他只出现了两次。玛丽不会被选中,因为她已经出现了 3 次。
-
我认为它是一个 dfs 图,其中节点是名称:)
标签: python-3.x tuples unique combinations