简体   繁体   English

如何展平元组列表并删除重复项?

[英]How to flatten a list of tuples and remove the duplicates?

I'm trying to remove the duplicates out of tuples in a list and add them in a new list with out duplicates, 我正在尝试从列表中的元组中删除重复项,并将它们添加到一个没有重复项的新列表中,

I tried to make two loops but and check for duplicates or sets but the problem there's three tuples 我尝试制作两个循环,但检查重复或设置,但问题是有三个元组

can anyone help me, I'm stuck here 任何人都可以帮助我,我被困在这里

example

[(2, 5), (3, 5), (2, 5)]

Output 产量

[2, 3, 5]

If order isn't important, you can make a set , add each element of each tuple to the set, and the set is your result. 如果顺序不重要,您可以创建一个set ,将每个元组的每个元素添加到集合中,集合就是您的结果。

s = set()
for tup in lst:
    for el in tup:
        s.add(el)
# or use a set comprehension:
# # s = {el for tup in lst for el in tup}

If order IS important, you can do mostly the same, but also have a result list to add to. 如果订单很重要,您可以大致相同,但也可以添加结果列表。

s = set()
result = []
for tup in lst:
    for el in tup:
        if el not in s:
            s.add(el)
            result.append(el)

You can use set comprehension: 你可以使用set comprehension:

lst = [(2, 5), (3, 5), (2, 5)]
{e for l in lst for e in l}

you need to iter through each tuple and then each element of tuple. 你需要通过每个元组,然后元组的每个元素。 before append just check if the element is in list: 在追加之前,只需检查元素是否在列表中:

a = [(2, 5), (3, 5), (2, 5)]
b = []
for i in a:
    for j in i:
        if j not in b:
           b.append(j)
print b

After running above code I got this output: 运行上面的代码后,我得到了这个输出:

[2, 5, 3]

An easy way to do so is using numpy ravel, and then set: 一个简单的方法是使用numpy ravel,然后设置:

import numpy as np
lst = [(2, 5), (3, 5), (2, 5)]
res = list(set(np.ravel(a)))

gives: 得到:

[2, 3, 5]

Answer to Apero's comment: 回答Apero的评论:

if you don't want to use numpy, you would be able to flatten the list with: 如果您不想使用numpy,您可以使用以下内容展平列表:

lst = [(2,5), (3,5), (2,5)]
tmp = []
for i in lst:
    for j in i:
        tmp.append(j)

res = set(tmp)
print res

which gives: 这使:

[2, 3, 5] 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM