根据另一个列表中的元素提取元组列表的元素

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

我有一个列表列表

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

和元组列表

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)]

我想从 list_tuples 中提取第一个元素列在 list_x 中的那些元组。 期望的输出是

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)]

我用 itemgetter (from operator import itemgetter) 试过了。它适用于字典,但我无法将其应用于此问题,因为它无法将列表用作列表索引(至少错误是这么说的)。

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

任何解决方案都很好(itemgetter 的解决方案会更好)。谢谢。

尝试:

list_output = [v for v in list_tuples if v[0] in list_x]
print(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),
]

使用过滤器,因为没有 v in v 逻辑

list(filter(lambda x: x[0] in list_x, list_tuples))

使用 itemgetter,我猜不是最快的,因为条目是列表而不是像元组那样可散列(感觉就像用右手从脑后触摸左耳)

list_x =  [['0', '2', '3'], ['8']]
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)]
list_x = list(map(lambda x: tuple(x), list_x))
list_tuples = list(map(lambda x: (tuple(x[0]), x), list_tuples))

itemgetter(*list_x)(dict(list_tuples))