Bangbangbang
Bangbangbang

Reputation: 560

check a list of values is in another nested list python and returns match

I have two lists of values

lst_a = [701221,310522,5272,8868,1168478,874766]
nested_lst_b = [[701221,310522,765272,12343],[8868,1168478,98023],[83645,5272],[63572,88765,22786]]

I want to check if every value in lst_a is in nested_lst_b and return the matched values

Expected outputs:

output = [[701221,310522],[8868,1168478],[5272],[]]

I wrote the coding below but it didn't get what I expected...

for x,y in zip(lst_a,nested_lst_b):
    if x in y:
        print(x,y)

>>>701221 [701221, 310522, 765272, 12343]
>>>5272 [83645, 5272]

Can anyone help me with the problem? Thanks so much

Upvotes: 1

Views: 760

Answers (2)

ScootCork
ScootCork

Reputation: 3686

One other solution would be using set.intersection, but it requires some casting between datatypes.

print([list(set.intersection(set(lst_a), set(b))) for b in nested_lst_b])

[[310522, 701221], [8868, 1168478], [5272], []]

Upvotes: 2

atru
atru

Reputation: 4744

This is one, simple way to do it based on your initial attempts:

lst_a = [701221,310522,5272,8868,1168478,874766]
nested_lst_b = [[701221,310522,765272,12343],[8868,1168478,98023],[83645,5272],[63572,88765,22786]]

a_in_b = []
for sub_lst_b in nested_lst_b:
    a_in_sub = []
    for el_a in lst_a:
        if el_a in sub_lst_b:
            a_in_sub.append(el_a)
    a_in_b.append(a_in_sub)

print(a_in_b)

Here you loop through every sublist of nested_lst_b and check if any element in lst_a is in that sublist. It follows your output requirements (nested list corresponding to nested_lst_b.

Otherwise, this type of problem may for instance be solved using sets.

Upvotes: 2

Related Questions