我有两个列表,其中一个具有另一个列表的子字符串。我想从列表B中提取所有具有匹配列表A中的子字符串的行。

例如,
清单A:

Sally Hope
Bob John
Seth Whale


清单B

[('Sally Hope does not like chocolate', 14)
('Sally Hope is great', 45)
('Seth Whale likes swimming', 43)
('Marley does not like walks', 56)
('John goes on walks', 55)]


输出:

[('Sally Hope does not like chocolate', 14)
('Sally Hope is great', 45)
('Seth Whale likes swimming', 43)]


我已经在R中使用amatch和dpylr过滤器对此进行了尝试,但未获得所需的输出,并且R在内存上使我失败(列表B有〜2m行)。在python中最有效的方法是什么?

最佳答案

Python有list comprehension

output = [j for i in list_a for j in list_b if i in j[0]]


结果

[('Sally Hope does not like chocolate', 14),
 ('Sally Hope is great', 45),
 ('Seth Whale likes swimming', 43)]

10-06 09:13