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

标签 python string substring

我有两个列表,其中一个包含另一个列表的子字符串。我想从列表 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)]

关于python - python中两个列表之间的部分字符串匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43908164/

相关文章:

C# 正则表达式 : Capture everything up to

c - C中的字符串终止-存储和匹配之间的区别

substring - ABL 子字符串 1 个字符到 2 个字符

java - 为什么这段代码不能正常工作?

python - 如何在服务器处理之前仅进行 "n"API 调用

python 3.3 : Birthday Probability

Python 等效于 R c() 函数,用于数据框列索引?

python - scipy.optimize 的最小化函数没有给出正确答案

c++ - 不同的字符串变量指向相同的地址

string - 如何拆分字符串并选择第 n 部分