Home > Mobile >  Finding elements from list in lists embedded in list (Python)
Finding elements from list in lists embedded in list (Python)

Time:10-01

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.

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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']]
  • Related