Skip to main content
 首页 » 编程设计

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

2025年02月15日25daizhj

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

例如, list 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 有列表理解,

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