Skip to content
Advertisement

Extract elements of a list of tuples based on elements in another list

I have a list of lists

list_x =  [['0', '2', '3'], ['8']]

and a list of tuples

list_tuples = [
(['0', '2', '3'], ['Start', '1', '2', '2', '9', '9', '9', '10', '15', 'End'], 1),
 (['8'], ['Start', '15', '16', '11', '2', '7', '1', 'End'], 2),
 (['1'], ['Start', '7', '1', '9', '4', '16', 'End'], 3),
 (['6'], ['Start', '15', '10', '7', 'End'], 4)]

I want to extract those tuples from list_tuples whose first element is listed in list_x. The desired output is

list_output = [
(['0', '2', '3'], ['Start', '1', '2', '2', '9', '9', '9', '10', '15', 'End'], 1),
 (['8'], ['Start', '15', '16', '11', '2', '7', '1', 'End'], 2)]

I tried it by using itemgetter (from operator import itemgetter). It works well with dicts but I could not apply it to this problem since it cannot work with a list as a list index (at least that is what the error said).

list_output = list(list_x, (itemgetter(*list_x)(list_tuples)))

Any solution would be great (a solution with itemgetter would be even greater). Thank you.

Advertisement

Answer

Try:

list_output = [v for v in list_tuples if v[0] in list_x]
print(list_output)

Prints:

[
    (
        ["0", "2", "3"],
        ["Start", "1", "2", "2", "9", "9", "9", "10", "15", "End"],
        1,
    ),
    (["8"], ["Start", "15", "16", "11", "2", "7", "1", "End"], 2),
]
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement