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.
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:
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:
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:
if you don't want to use numpy, you would be able to 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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.