1

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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Gladly! Careful with zip btw., I thought it throws if the lists aren't the same length, but no, it will just iterate until the end of the shortest.
2

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], []]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.