junkfoodjunkie
junkfoodjunkie

Reputation: 3178

Getting unique values from specific point in a nested list

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 nrand 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

Answers (2)

Avi Turner
Avi Turner

Reputation: 10456

Try:

list(set(tpl[0] for tpl in mylist))

Explanation:
Break the problem into stages:

  1. Get all items at index 0 from you nested lists:

    first_items_in_nested = (tpl[0] for tpl in mylist)  
    
  2. Get the unique values from step 1:

    unique_items = set(first_items_in_nested)
    
  3. (optional) Convert results back to a list:

    result = list(unique_items)
    

Upvotes: 1

John R
John R

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

Related Questions