简体   繁体   English

如何从对列表中检索对组合,而没有任何单个元素在一对以上?

[英]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.

相关问题 如何从一对中的单个元素,从嵌套在父列表中的众多对中生成所有可能组合的列表? - How do I generate a list of all possible combinations from a single element in a pair, from numerous pairs nested within a parent list? 如何从字典中检索多个项目对 - How do I retrieve more than one item pair from a dictionary 如何检查任何键值对是否在字典列表中多次出现? - How do I check if any key-value pair appears more than once in a list of dictionaries? 我如何从一群人中分配每周配对,以便每对在 Python 中相遇并且没有一对相遇超过一次 - How would I assign weekly pairs from a group of people so that each pair meets and no pair meets more than once in Python 在python中查找数字列表的所有组合而不是相同的组合 - Finding all combinations of a list of numbers without the pair being the same in python 列表中的一个元素与其他元素配对 - one element from list pair with other elements 如何访问配对列表中配对的每个元素? - How can I access each element of a pair in a pair list? 如何使用单个键:值对从字典项列表中提取一项? - How can I pull one item, from a list of dictionary items, using a single key:value pair? 获取 m 个列表的 r 长度元组组合,任何列表中不超过一个元素,并且 r &lt; m - Get r-length tuple combinations of m lists, with no more than a single element from any list, and r < m 嵌套列表中的唯一性具有不超过一对重叠的坐标 - Uniqueness in nested list to have no more than one overlapping pair of coordinates
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM