Reputation: 469
So I have a list of tuples of tuples that looks like this:
f = [
((0, 0), 5, "S"),
((1, 0), 10, "SN"),
((0, 0), 8, "SS"),
((3, 4), 9, "WN")
...
]
What I want to basically do make a unique list, where the uniqueness of each element of the list depends on the first tuple. For example, from the list above, I need the output to be this:
f = [
((0, 0), 5, "S"),
((1, 0), 10, "SN"),
((3, 4), 9, "WN")
...
]
Since (0,0) is already there in the list (at index 0), the other (0,0) should not be appended.
Below is the code that I have tried, but it doesn't seem to work:
f = [...]
for i in f:
if i[0] == (0,0):
continue
else:
f.append(((0,0), val, st))
Can anyone tell me where I'm going wrong or what is the better way of approaching this?
Upvotes: 0
Views: 98
Reputation: 51645
Using itertools
:
>>> from itertools import groupby
>>> keyfunc = lambda x: x[0]
>>> data = sorted(f, key=keyfunc)
>>> new_f = [ next(v) for _,v in groupby(data, keyfunc) ]
Results:
>>> new_f
[((0, 0), 5, 'S'), ((1, 0), 10, 'SN'), ((3, 4), 9, 'WN')]
Upvotes: 0
Reputation: 22766
You can use a set()
for a fast inclusion check:
seen = set()
new = []
for t in f:
if t[0] not in seen:
seen.add(t[0])
new.append(t)
print(new)
Output:
[((0, 0), 5, 'S'),
((1, 0), 10, 'SN'),
((3, 4), 9, 'WN')]
Upvotes: 4