python中两个列表之间的部分字符串匹配

时间:2017-05-11 06:36:27

标签: python string substring

我有两个列表,其中一个列表包含另一个列表的子串。我想从列表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中执行此操作的最有效方法是什么?

1 个答案:

答案 0 :(得分:1)

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