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

The title of the question is pretty much what I'm interested in!

Let's say I have a list of tuples:

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

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

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

Is it possible? Is there a simple expression or will I need to go through tuple_list and create a separate list of the first elements this way?

Also, the reason I want to do this is because I want 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 that used 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] 

Therefore, my dilemma with the lack of .key () for lists

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

Thanks,

Alex

+4
source share
2 answers

Yes it is possible.

Use 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 will be faster:

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

Note that if you do this several times, you can convert first_list to dict :

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

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]) 
+2
source

Source: https://habr.com/ru/post/1490977/


All Articles