I have a list of lists
JavaScript
x
2
1
list_x = [['0', '2', '3'], ['8']]
2
and a list of tuples
JavaScript
1
6
1
list_tuples = [
2
(['0', '2', '3'], ['Start', '1', '2', '2', '9', '9', '9', '10', '15', 'End'], 1),
3
(['8'], ['Start', '15', '16', '11', '2', '7', '1', 'End'], 2),
4
(['1'], ['Start', '7', '1', '9', '4', '16', 'End'], 3),
5
(['6'], ['Start', '15', '10', '7', 'End'], 4)]
6
I want to extract those tuples from list_tuples
whose first element is listed in list_x
.
The desired output is
JavaScript
1
4
1
list_output = [
2
(['0', '2', '3'], ['Start', '1', '2', '2', '9', '9', '9', '10', '15', 'End'], 1),
3
(['8'], ['Start', '15', '16', '11', '2', '7', '1', 'End'], 2)]
4
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).
JavaScript
1
2
1
list_output = list(list_x, (itemgetter(*list_x)(list_tuples)))
2
Any solution would be great (a solution with itemgetter
would be even greater). Thank you.
Advertisement
Answer
Try:
JavaScript
1
3
1
list_output = [v for v in list_tuples if v[0] in list_x]
2
print(list_output)
3
Prints:
JavaScript
1
9
1
[
2
(
3
["0", "2", "3"],
4
["Start", "1", "2", "2", "9", "9", "9", "10", "15", "End"],
5
1,
6
),
7
(["8"], ["Start", "15", "16", "11", "2", "7", "1", "End"], 2),
8
]
9