简体   繁体   中英

Comparing elements between elements in two lists of tuples

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

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'])

I think it is probably clearer to use sets here (since you have no duplicate elements):

set1 = set( el[0] for el in list1 )
set2 = set( el[0] for el in list2 )
set3 = set1 & set2 # set intersection
# list3 = list(set3)

Assuming that you want the set intersection of the first elements of the tuples, you can use the dictionary key views introduced in Python 2.7:

dict(list1).viewkeys() & dict(list2).viewkeys()

This will be much more efficient than your solution for long lists, since it has linear runtime (as opposed to O(mn) for your solution), but returns the result in arbitrary order (as opposed to the order defined by list1 ).

In Python 3.x, this would be

dict(list1).keys() & dict(list2).keys()

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