How would I remove all occurrences in a list of tuples where the second element in the tuple is repeated?
I have:
a = [('a',1),('b',3),('c',1),('d',1),('e',5),('f',1)]
I am trying to return
[('b',3),('e',5)]
I tried
a = list(set(a))
But doesn't remove all occurrences, is there a way to do that without importing any libraries?
Try the following:
a = [('a',1),('b',3),('c',1),('d',1),('e',5),('f',1)]
reduced = [y for x in a for y in x]
[x for x in a if reduced.count(x[0]) == 1 and reduced.count(x[1]) == 1]
# [('b', 3), ('e', 5)]
This flattens your original list of tuples into one list. It then iterates through the original list, and for each tuple it checks to see if either of its elements is in the flattened list only once. If so, it keeps it; otherwise, it discards it.
You can also use python dictionaries for this (if the first elements of the inner tuples are different from one another):
list({k:v for k,v in dict(a).items() if list(dict(a).values()).count(v)==1}.items())
The idea here is to convert your list of tuples into a dictionary and keep the key-value
pairs where the count
of the value
part in the dictionary's values
is 1.
I hope this helps.
Hmm, how about:
def UniqueTuples(tuples):
seen, unique = set(), list()
for x, y in tuples:
if y not in seen:
seen.add(y)
unique.append((x, y))
return unique
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.