简体   繁体   中英

Creating a new list based on matching elements of two nested lists in Python?

I have two lists, each containing multiple sublists of two elements each. I want to create a new list that contains only those sublists where the first element of the sublist existed in both original lists. I can do it in flat lists using list comprehension or set intersections, but struggle when it is with lists of lists.

For example (using data from a csv file):

apairs = [['apple', '2.4\n'], ['banana', '2.3\n'], ['orange', '1.8\n'], 
          ['apple', '1.6\n']]
bpairs = [['grape', '2.3\n'], ['apple', '2.1\n'], ['apple', '2.0\n'],
          ['peach', '1.9\n'], ['plum', '1.5\n']]

I would like a new list created that includes only the pairs where the first element of a sublist exists in both outer lists and only the first instance of a pair with element is included. I want the pair to be extracted from the 'alist' so that it includes the second element of that pair. So my desired output in this case is:

intersectpairs = [['apple, '2.4\n']]

Any help would be appreciated!

intersectpairs = []
bfruits = set()

for i in range(0,len(bpairs)):
    bfruits.add(bpairs[i][0])

for i in range(0,len(apairs)):
    if apairs[i][0] in bfruits:
       intersectpairs.append(apairs[i])

print (intersectpairs)

You can simply iterate over both the list and compare the value. A sample code snippet for the same is :

apairs = [['apple', '2.4\n'], ['banana', '2.3\n'], ['orange', '1.8\n']]
bpairs = [['grape', '2.3\n'], ['apple', '2.1\n'], ['peach', '1.9\n'], ['plum',     '1.5\n']]
intersectpairs = []
for i in apairs:
    for j in bpairs:
        if (i[0]==j[0]):
            intersectpairs.append(i)
print(intersectpairs)

[['apple', '2.4\n']]

Or if you want to use list comprehension

[i for i in apairs for j in bpairs if(i[0]==j[0])] 

This would return a list of list with matching element in both the list.

How about list comprehension?

from operator import itemgetter

first = itemgetter(0)

[val for val in apairs if first(val) in map(first, bpairs)]

[['apple', '2.4\n']]

Thanks for the help everyone! I figured out a solution based on @Mayank Mehtani's answer. For people with this problem in the future, this code solves the problem:

intersectionpairs = []
intersectionfruits = []
bfruits = set()

for i in range(0,len(bpairs)):
    bfruits.add(bpairs[i][0])
print('bfruits:', bfruits)
for i in range(0,len(apairs)):
    if apairs[i][0] in bfruits and apairs[i][0] not in intersectionfruits:
        intersectionfruits.append(apairs[i][0])
        intersectionpairs.append(apairs[i])

May not be the most efficient or sophisticated answer, but it gives the desired output!

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