Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing elements between elements in two lists of tuples

Tags:

python

Here is what I am looking to do.I have two list of tuples. Build a list of elements such that the first element in a tuple in list1 matches the first element in a tuple in list 2

list1 = [('a', 2), ('b', 3), ('z', 5)]

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

list3 = ['a','b']

Note: There can be no duplicate first elements

After looking at python list comprehensions, this is what I have done

[x[0] for x in list1 if (x[0] in [y[0] for y in list2])]

My questions is would this be how an experienced python programmer would code this up? Having coded this up myself I still find this fairly hard to read. If not how else would you do it

like image 317
sidg11 Avatar asked Oct 31 '12 22:10

sidg11


People also ask

How we can compare items of two tuples?

Tuples are compared position by position: the first item of the first tuple is compared to the first item of the second tuple; if they are not equal, this is the result of the comparison, else the second item is considered, then the third and so on.

How do you compare two list tuples in Python?

Method #1 : Using == operator This is the simplest and elegant way to perform this task. It also checks for equality of tuple indices with one other.

How do you compare items in two lists?

counter() method can be used to compare lists efficiently. The counter() function counts the frequency of the items in a list and stores the data as a dictionary in the format <value>:<frequency>. If two lists have the exact same dictionary output, we can infer that the lists are the same.


2 Answers

I'd use zip():

In [25]: l1 = [('a', 2), ('b', 3), ('z', 5)]

In [26]: l2 = [('a', 1), ('b', 2), ('c', 3)]

In [27]: [x[0] for x,y in zip(l1,l2) if x[0]==y[0]]
Out[27]: ['a', 'b']

EDIT: After reading your comment above it looks like you're looking for something like this:

In [36]: [x[0] for x in l1 if any(x[0]==y[0] for y in l2)]
Out[36]: ['a', 'b']

or using sets:

In [43]: from operator import itemgetter

In [44]: set(map(itemgetter(0),l1)) & set(map(itemgetter(0),l2))
Out[44]: set(['a', 'b'])
like image 66
Ashwini Chaudhary Avatar answered Nov 15 '22 08:11

Ashwini Chaudhary


I think you want to use sets here:

set(x[0] for x in list1).intersection(y[0] for y in list2)

or using syntactic sugar:

{x[0] for x in list1} & {y[0] for y in list2}

Both of which result in:

set(['a', 'b'])
like image 42
Eric Avatar answered Nov 15 '22 08:11

Eric