[英]How do I retrieve pair combinations from a list of pairs without any single element being in more than one pair?
If I have a list of pairs, such as如果我有一个配对列表,例如
[(egg,man),(egg,dog),(cat,cactus),(cactus,elephant),(giraffe,chocolate),(tea,boat),(sky,lizard),(sky,tree),(helicopter,lizard)]
How would I retrieve the most amount of pairs possible without any single element being in more than one pair?在没有任何单个元素超过一对的情况下,我将如何检索尽可能多的对? What I would want to retrieve is something like this:
我想要检索的是这样的:
(egg,man),(cat,cactus),(giraffe,chocolate),(tea,boat),(sky,lizard)
So that every pair only contains unique elements, and I get the most possible.这样每一对都只包含独特的元素,我得到了最大的可能。
This worked for me:这对我有用:
words = [('egg','man'),('egg','dog'),('cat','cactus'),('cactus','elephant'),('giraffe','chocolate'),('tea','boat'),('sky','lizard'),('sky','tree'),('helicopter','lizard')]
new_words = []
count = 0
for i in range(len(words)):
for k in range(len(words[i])):
if words[i][k] not in [item for t in new_words for item in t]:
count += 1
if count == 2:
new_words.append(words[i])
count = 0
The list new_words
is the list that you want.列表
new_words
是您想要的列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.