简体   繁体   中英

Finding elements from list in lists embedded in list (Python)

Is there any simple function to iterate through lists embedded in a list in Python? I have a list

A = ["apple", "banana", "cherry"] .

Then, I want check which elements could be found in list of lists

B = [["banana", "cherry", "pear"], ["banana"," orange']] .

The result should be sth like this: c = [["banana", "cherry"], ["banana"]] .

Thanks for your help.

You can do this with a list comprehension:

[
   [ b
     for b in l # loop over items in the sub list
     if b in A] # Check in they are in the main list
   for l in B # Loop over the big list
]

This will maintain correct order, and also preserve empty lists

You can loop over list B and do a set intersection and retain results if there is a match. Note that set will disrupt the order of items.

C = []
for item in B:
    common = set(item).intersection(A)
    if len(common) > 0:
        C.append(list(common))

print(C) # [['banana', 'cherry'], ['banana']]

Iteration in given lists A & B doable sth like this;

A = ["apple", "banana", "cherry"]

B = [["banana", "cherry", "pear"], ["banana","orange"]]

C = []
for i in B:
    C_temp = []
    for j in A:
        if j in i:
            C_temp.append(j)
    C.append(C_temp)
print(C)

Output of C;

[['banana', 'cherry'], ['banana']]

Here is using map , lambda , set , and list function to iterate through lists:

A = ["apple", "banana", "cherry"]
B = [["banana", "cherry", "pear"], ["banana",'orange']]
C = list(map(lambda c: sorted(list(set(A).intersection(c))), B))

# [['banana', 'cherry'], ['banana']]

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