How to smooth the list of tuples and remove duplicates?

I am trying to remove duplicates from tuples in a list and add them to a new list without duplicates,

I tried to make two loops, but also check for duplicates or sets, but the problem there is three tuples

Can someone help me, I'm stuck here

Example

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

Output

 [2, 3, 5] 
+5
source share
4 answers

If the order is not important, you can make set , add each element of each tuple to the set, and the set is your result.

 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 basically the same thing, but also add a list of results.

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

You can use many concepts:

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

you need to iterate through each tuple, and then each element of the tuple. before adding just check if the item is in the 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 on the code, I got this output:

 [2, 5, 3] 
+2
source

An easy way to do this is to use numpy ravel and then install:

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

gives:

 [2, 3, 5] 

Reply to Apero comment:

If you do not want to use numpy, you can flatten the list with:

 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] 
+1
source

Source: https://habr.com/ru/post/1246429/


All Articles