![](/img/trans.png)
[英]Python match similar strings and group them together from two lists
[英]Find Similar Strings In Two Python Lists
我有一个要在另一个列表中查找的单词列表。 我想在我的 main_list 中找到 match_words 并在新列表中返回它们的值。
match_words = ['reports', 'users']
main_list = ['reports_data', 'users_accounts', 'backups', 'logs']
返回的正确值应该是
returned_list = ['reports_data', 'users_accounts']
我试过使用
returned_list = filter(lambda x:x in main_list,match_words)
我假设它们不匹配,因为它们不是完全匹配的关键字?
有点冗长,但它可以完成工作
match_words = ['reports', 'users']
main_list = ['reports_data', 'users_accounts', 'backups', 'logs']
returned_list = []
for i in match_words:
for j in main_list:
if i in j:
returned_list.append(j)
目前尚不清楚您的相似性度量是什么,但是,假设您只需要一个匹配的前缀,您可以使用以下列表理解
returned_list = [word for pre in match_words for word in main_list if word.startswith(pre)]
编辑:
如果您需要检查一个字符串是否是另一个字符串的一部分,您可以使用in
运算符
returned_list = [word for part in match_words for word in main_list if part in word]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.