比较字符串中的字符

Sc4*_*c4r 0 python string list

给定两个字符串作为参数返回true如果第一个字可以通过改变一个字母从第二个字形成.我接近这个的方式是:

def differ(word_one, word_two):
    '''(str, str) -> bool

    Returns true iff word_two can be formed from word_one by changing
    exactly one letter.

    >>> differ('cat', 'bat')
    True
    >>> differ('word', 'sword')
    False

    '''
    temp_list = []
    # If the length of the first string is equal to the length of the
    # second string, iterate over the letters in the first string and
    # if the letter in the first string does not equal to the letter 
    # in the second string append the letter to temp_list
    if len(word_one) == len(word_two):
        for char in word_one:
            if char != word_two[word_one.index(char)]:
                temp_list.append(char)
    if len(temp_list) == 1:
        return True
    else:
        return False
Run Code Online (Sandbox Code Playgroud)

根据描述,我的代码似乎工作得很好,但有一个更简化的方法吗?

mgi*_*son 5

看起来很简单zip(加上一些长度检查),不是吗?

sum(a != b for a, b in zip(word1, word2)) == 1
Run Code Online (Sandbox Code Playgroud)

这不依赖于有些模糊的事实是,在运算环境,
True == 1False == 0.例如True + True + True + False == 3

例:

>>> def differ(word1, word2):
...     return ((len(word1) == len(word2)) and 
...             (sum(a != b for a, b in zip(word1, word2)) == 1))
... 
>>> differ('cat', 'bat')
True
>>> differ('cat', 'hat')
True
>>> differ('cat', 'can')
True
>>> differ('cat', 'car')
True
>>> differ('cat', 'bar')
False
Run Code Online (Sandbox Code Playgroud)