我自己喜欢切片。使用返回 True/False 的函数来过滤列表中您需要/想要的条件。
orig = 'abcdef#ghijklmn'
test = 'abcdef%ghijklmn'
test_bad = 'abcdef%ghijk*mn'
def one_letter_different(s1, s2):
"""returns True if there is only one letter different between s1 and s2.
Sequentially check each letter of each string till they don't match
then check to see if the rest of the strings are equal.
s1, s2 -> str
"""
for i, c in enumerate(s1):
if c != s2[i]:
# test for substituition, deletion and insertion
return (s1[i + 1:] == s2[i + 1:] or
s1[i:] == s2[i + 1:] or
s1[i+1:] == s2[i:])
# s1 equals s2
return False
print one_letter_different(orig, test)
print one_letter_different(orig, test_bad)
test = 'take'
print [item for item in ['fake','bake','sake','rake']
if one_letter_different(item, test)]
test = 'bare'
print [item for item in ['fake','bake','sake','rake']
if one_letter_different(item, test)]
产生:
>>>
True
False
['fake', 'bake', 'sake', 'rake']
['bake']
>>>
比较函数也可以定义为:
from operator import ne
from itertools import izip_longest
def one_letter_different(s1, s2):
"""returns True if there is less than two letters different.
Sequentially compare the letters of each string and sum the differences.
s1, s2 -> str
"""
return sum(ne(*thing) for thing in izip_longest(s1, s2, fillvalue = None)) == 1