遍历字符串并打印字符之间的距离

Ral*_*eng 5 python

source = 'abc'

def editDistance(source, target):
    items1=[]
    for c in range(0,len(source)):
        for k in range(1,len(source)):
            if (k < len(source)):
                test = ord(source[k]) - ord(source[c])
                items1.append(test)    
    return items1
Run Code Online (Sandbox Code Playgroud)

我试图遍历字符串并找到字母表中每个字符之间的距离。a因此,和之间的距离b是, 和之间1的距离是。我想打印出一系列,但是,我认为我弄乱了 for 循环及其打印输出:。bc1[1, 1][1, 2, 0, 1, -1, 0]

Dea*_*ool 2

您可以使用列表理解,通过使用ordfor 转换asciiintabs函数

[abs(ord(source[i])-ord(source[i+1])) for i in range(len(source)-1)]
Run Code Online (Sandbox Code Playgroud)

或者使用for循环

for c in range(len(source)-1):
    test = ord(source[c]) - ord(source[c+1])
    items1.append(abs(test))  
return items1
Run Code Online (Sandbox Code Playgroud)

或者您可以导入string并使用string.ascii_lowercase来查找index

string.ascii_lowercase.index('b')  # 1
Run Code Online (Sandbox Code Playgroud)