python - 如何检查一个字符串中的字母是否在另一字符串中

标签 python python-2.7 python-3.x

我有一个按字母顺序排列的单词列表,例如 hello = ehllo 我如何检查这个单词“blanagrams”,这些单词除了 1 之外几乎所有字母都相似。例如, Orchestra 变成了 orchestre。我只能想到这一部分。我有一个想法,你必须测试当前单词的每个字母,看看它是否与另一个对应,如果是,它就是一个 blanagram 并创建一个字典,但我正在努力将其放入代码

L = [list of alphabetically ordered strings]

for word in L:

     for letter in word:
        #confused at this part

最佳答案

from collections import Counter
def same_except1(s1, s2):
    ct1, ct2 = Counter(s1), Counter(s2)
    return sum((ct1 - ct2).values()) == 1 and sum((ct2 - ct1).values()) == 1

示例:

>>> same_except1('hello', 'hella')
True
>>> same_except1('hello', 'heela')
False
>>> same_except1('hello', 'hello')
False
>>> same_except1('hello', 'helloa')
False

关于python - 如何检查一个字符串中的字母是否在另一字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41022333/

相关文章:

python - 从 Google Cloud Function python3.7 连接到 Google Cloud SQL

python - 使用 numpy argsort 出现内存错误

python - 使用 Python 读取 MS-Word 文件中页眉和页脚中的表格内容

python - 如何将 Memcache 与 ProtoRPC 结合使用(Google App Engine - Python)

python - 如何让 python 描述符知道所属类的实例已被删除

python - 优化 Python 代码以提高效率

python - numpy.r_ 不是函数。它是什么?

python - 不使用嵌套循环读取文件和文件夹

python - 使用 mock.patch 和 mock_open 模拟包含 JSON 数据的文件

python - NumPy 数组索引 4D 数组