【问题标题】:find repeated element in list of list python在列表python列表中查找重复的元素
【发布时间】:2016-10-19 14:07:13
【问题描述】:

我已经为这个问题苦苦挣扎了两天,我需要帮助。我需要在列表列表中找到重复的元素 list_of_list = [(a1, b1, c1), (a2, b2, c2), ..., (an, bn, cn)] 其中“a”和“b”元素是整数,“c”元素是浮点数。

因此,例如a1 == a2a1 == bn,我需要创建一个包含整个列表元素的新列表,并且我需要对列表列表中的所有列表(a、b、c)进行迭代。换句话说,我需要所有包含多个列表中的元素的列表。我只需要比较“a”和“b”元素,但在最终列表中获得关联值“c”。

例如:

list_of_list = [(1, 2, 4.99), (3, 6, 5.99), (1, 4, 3.00), (5, 1, 1.12), (7, 8, 1.99) ]

desired_result=[(1, 2, 4.99), (1, 4, 3.00), (5, 1, 1.12)] 

我尝试了很多想法......但没有什么好主意:

MI_network = [] #repeated elements list
genesis = list(complete_net) #clon to work on
genesis_next = list(genesis) #clon to remove elements in iterations
genesis_next.remove(genesis_next[0])

while genesis_next != []:
    for x in genesis:
        if x[0] in genesis_next and x[1] not in genesis_next:
            MI_network.append(x)
        if x[0] not in genesis_next and x[1] in genesis_next:
            MI_network.append(x)
    genesis_next.remove(genesis_next[0])

【问题讨论】:

  • desired_result 包含完整的结果,还是只包含其中的一部分?
  • 只需要与a1值比较?
  • 你的意思是ai = ajai = bj for i, j in (1, n) 吗?
  • 1-想要的结果有完整的结果 2-我需要将所有 a 元素与所有列表中的所有 a 和 b 元素进行比较

标签: python list element


【解决方案1】:

根据你的想法,你可以试试这个:

MI_network = []
complete_net = [(1, 2, 4.99), (3, 6, 5.99), (1, 4, 3.00), (5, 1, 1.12), (7, 8, 1.99)]
genesis = list(complete_net)

while genesis != []:
    for x in genesis:
        for gen in genesis:
            if x[0] in gen and x[1] not in gen:
                if x[0] != gen[2] and x[1] != gen[2]:
                    if x not in MI_network:
                        MI_network.append(x)
            elif x[0] not in gen and x[1] in gen:
                if x[0] != gen[2] and x[1] != gen[2]:
                    if x not in MI_network:
                        MI_network.append(x)
            elif x[0] not in gen and x[1] not in gen:
                pass
    genesis.remove(genesis[0])   

print(MI_network)
[(1, 2, 4.99), (1, 4, 3.0), (5, 1, 1.12)]

【讨论】:

    【解决方案2】:

    这就是我的做法,因为我不知道collections.defaultdict()

    list_of_list = [(1, 2, 4.99), (3, 6, 5.99), (1, 4, 3.00), (5, 1, 1.12), (7, 8, 1.99) ]
    results = []
    for i_sub, subset in enumerate(list_of_list):
    # test if ai == aj
        rest = list_of_list[:i_sub] + list_of_list[i_sub + 1:]
        if any(subset[0] == subrest[0] for subrest in rest):
            results.append(subset)
    # test if ai == bj
        elif any(subset[0] == subrest[1] for subrest in rest):
            results.append(subset)
    # test if bi == aj
        elif any(subset[1] == subrest[0] for subrest in rest):
            results.append(subset)
    print(results)  # -> [(1, 2, 4.99), (1, 4, 3.0), (5, 1, 1.12)]
    

    【讨论】:

    • 谢谢,我正在尝试“破解”这段代码,因为我无法 100% 理解它,但目前它工作得很好。
    • 我将这种方法与@nicost 进行了比较,两者都给了我不同的结果。虽然 nicost 给了我一个重复的列表,但是这个脚本没有检测到这样的列表。