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
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.
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.
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.
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'])
I think you want to use set
s 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'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With