简体   繁体   中英

Referring to the first element of all tuples in a list of tuples

The question title is pretty much what I'm wondering!

Say I have a list of tuples:

tuple_list = [(1,'a'),(2,'b'),(3,'c')]

What would I use to refer to all of the first elements of tuple_list? What I would like returned is a list of first elements. Just like tuple_list.keys() would work if it were a dictionary. Like this:

(tuple_list expression here) = [1,2,3]

Is this possible? Is there a simple expression or would I have to iterate through the tuple_list and create a separate list of first elements that way?

Furthermore, the reason I am wanting to do this is because I am wanting to do the following:

first_list = [(1,'a'),(2,'b'),(3,'c')]
second_list = [1,2,3,4,4,5]

third_list = set(second_list) - set(first_list(**first elements expression**)) = [4,5]

I am adapting this for lists from some old code which was using dictionaries:

first_dict = {1:'a',2:'b',3:'c'}
second = [1,2,3,4,4,5]

third_dict = set(second) - set(first_dict.keys()) = [4,5]

Hence my dilemma with a lack of .key() for lists

As always, please comment if I can improve/clarify the question in any way.

Thanks,

Alex

Yes , it is possible.

Use a list comprehension:

>>> tuple_list = [(1,'a'),(2,'b'),(3,'c')]
>>> [x[0] for x in tuple_list]
[1, 2, 3]

or:

>>> from operator import itemgetter
>>> f = itemgetter(0)
>>> map(f, tuple_list)
[1, 2, 3]

Your example:

>>> first_list = [(1,'a'),(2,'b'),(3,'c')]
>>> second_list = [1,2,3,4,4,5]
>>> set(second_list) - set(x[0] for x in first_list)
set([4, 5])
>>> set(second_list) - set(map(f, first_list))
set([4, 5])

or As suggested by @JonClements, this going to be faster:

>>> set(second_list).difference(map(f, first_list))
set([4, 5])

Note that if you're doing this multiple time then you can convert first_list to a dict :

>>> dic = dict(first_list)
>>> set(second_list).difference(dic)
set([4, 5])

You can try this list comprehension:

tuple_list = [(1,'a'),(2,'b'),(3,'c')]
desired_list = [ x for x, _ in tuple_list ] 

You can also use map :

desired_list = map(lambda(x,_):x, tuple_list)

Based on your edit, you can do this:

>>> first_list = [(1,'a'),(2,'b'),(3,'c')]
>>> second_list = [1,2,3,4,4,5]
>>> third_list = set(second_list).difference(x for x, _ in first_list)
>>> third_list
set([4, 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM