比较忽略某些字符的单词 - Python

Compare words ignoring certain characters - Python

我在 python 中看到过几个类似的问题,但 none。基本上,我想检查某些单词是否在列表中。虽然我想比较的词可能有一个 ',',但我想忽略它。我试过这个,虽然它不会忽略','。

x = ['hello','there,','person']
y = ['there','person']
similar = [words for words in x if words in y ]
print(similar)

输出

['person']

但是我想要

['there','person']

有谁知道最简单的实现方法吗?

只比较没有逗号的字符串:

similar = [words for words in x if words.replace(',', '') in y ]

输出:

>>similar
['there,', 'person']

检查此代码使用 any functionmap 映射包含条件。

x = ['hello','there,','person']
y = ['there','person'] # or take this for more intuation ['there','person','bro']
similar = [words for words in y if any(map(lambda i: i.count(words), x))]
print(similar)

输出:

['there', 'person']

到目前为止,其他两个答案需要 O(n x m) 的二次时间复杂度,其中 n m分别是xy的长度。

对于只需要 O(n + m) 线性时间复杂度的解决方案,您可以将 x 中的字符串标准化为不带逗号的字符串并存储它们作为一个集合,这样您就可以使用集合交集来查找具有 y:

的常见字符串
similar = {word.replace(',' ,'') for word in x}.intersection(y)