How to pull a list with in a list by matching one value in an external list, in Python?

Viewed 27

My data is a large (linked) list, that is made up of smaller lists (7500+). And within these smaller lists exists another list with strings as their value. List A <-- List B's <-- List C (names).

List_A = [['123', 'Hello World', '2020', ['john', 'mike', 'edgar'], 'N'],
          ['124', 'Hello Universe', '2021', ['harold', 'jessica', 'ashley'], 'Y'],
          ['125', 'Hello Milkyway', '2020', ['maria', 'tessa', 'rodrigo'], 'N']]

List_A.nodeat(0).value[3]
>>>> ['john', 'mike', 'edgar']

Outside this large list, I've created a string split list of names:
List_Outside = ['mike', 'maria']. 

I want to create a new list (List_A_2) of only List B's that have at least one matching name from List_Outside in List C.

So List_A_2 would look like:

List_A_2 = [['123', 'Hello World', '2020', ['john', 'mike', 'edgar'], 'N'],
           ['125', 'Hello Milkyway', '2020', ['maria', 'tessa', 'rodrigo'], 'N']]

Of course I would like this to be applicable for 7500+ lists so I would need to use indexes in a for loop. Thanks in advance.

1 Answers

You can use any() to filter the list:

List_A_2 = [l for l in List_A if any(w in List_Outside for w in l[3])]
print(List_A_2)

Prints:

[['123', 'Hello World', '2020', ['john', 'mike', 'edgar'], 'N'], 
['125', 'Hello Milkyway', '2020', ['maria', 'tessa', 'rodrigo'], 'N']]
Related