Reputation: 3178
I have a list like this:
$ mylist = [(u'nr',<object>,'string1'),(u'fm',<object>,'string2'),(u'nr',<object>,'string3')]
I would like to get the unique values of nr
and fm
from that list (ie, no repeat ones for that first element).
I've been looking at getting unique lists using set()
and such, and I tried this (from another thread):
$ unique = reduce(lambda l, x: l.append(x) or l if x not in l else l, mylist, [])
but that didn't work.
Was asked to clarify: I want ['nr','fm'] in the final result
Upvotes: 0
Views: 249
Reputation: 10456
Try:
list(set(tpl[0] for tpl in mylist))
Explanation:
Break the problem into stages:
Get all items at index 0 from you nested lists:
first_items_in_nested = (tpl[0] for tpl in mylist)
Get the unique values from step 1:
unique_items = set(first_items_in_nested)
(optional) Convert results back to a list:
result = list(unique_items)
Upvotes: 1
Reputation: 1508
This will yield the unique, first values of a list of tuples:
set(x[0] for x in mylist)
If you want it back to a list:
list(set(x[0] for x in mylist))
Upvotes: 1