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

5
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

我试图迭代字符串并找到每个字符在字母表中的距离。因此,ab之间的距离是1bc之间的距离也是1。我想打印出一个数组[1, 1],但我认为我的for循环有问题,它打印出了[1, 2, 0, 1, -1, 0]


你能提供一份输入样例吗? - dmigo
1
您正在获取字符串中每个字符和其他每个字符之间的距离。如果您只想要一个字符和下一个字符之间的距离,那么您只需要一个for循环即可。 - Code-Apprentice
请注意,if (k < len(source)): 是不必要的,因为条件始终为真。 - Code-Apprentice
另外,你有一个名为 target 的参数,但你从未使用过它。你可以将其删除或者你可能遗漏了一些需要完成的任务。 - Code-Apprentice
5个回答

3

这不就像是这样简单吗:

alphabet = 'abcdefghijklmnopqrstuvwxyz'
abs(alphabet.index('z') - alphabet.index('a'))

这是一个概念验证:
Python 3.7.4 (default, Aug 12 2019, 14:45:07) 
[GCC 9.1.1 20190605 (Red Hat 9.1.1-2)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> alphabet = 'abcdefghijklpmnopqrstuvwxyz'
>>> abs(alphabet.index('z') - alphabet.index('a'))
26
>>> abs(alphabet.index('a') - alphabet.index('c'))
2
>>> abs(alphabet.index('c') - alphabet.index('a'))
2
>>> 

实际上,它适用于任何字符集,无论大小写或类别如何:

Python 3.7.4 (default, Aug 12 2019, 14:45:07) 
[GCC 9.1.1 20190605 (Red Hat 9.1.1-2)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> s='ABCdefgh!çõ'
>>> abs(s.index('ç') - s.index('A'))
9
>>> abs(s.index('B') - s.index('A'))
1
>>> abs(s.index('B') - s.index('!'))
7
>>> abs(s.index('!') - s.index('B'))
7
>>> 

1
这仅适用于小写字母。OP的示例只包含小写字母,但他们没有指定这种情况始终如此。 - mypetlion
这适用于任何一组字符,无论大小写或类别如何。 - accdias
它适用于您提供的任何“字母表”(在alphabet变量中),在您的情况下,那就是小写拉丁字母表。重点是,OP没有指定他们可能需要什么字母表。 - mypetlion

2

您可以使用列表推导式,通过使用ordascii转换为int并使用abs函数来实现。

[abs(ord(source[i])-ord(source[i+1])) for i in range(len(source)-1)]

或通过使用 for 循环

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

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

string.ascii_lowercase.index('b')  # 1

1
def char_distanc(word):
    result =[]
    for i, char1 in enumerate(word):
        tmp =[]
        for j, char2 in enumerate(word):
            tmp.append(abs(ord(char1)-ord(char2)))
        result.append(tmp)
    return result

word = "abc"
print(char_distanc(word))

输出

[[0, 1, 2], [1, 0, 1], [2, 1, 0]]

视觉解释
    'a' 'b' 'c'
'a'  0   1   2
'b'  1   0   1
'c'  2   1   0

@DerekEden 只需加上 if i!=j 条件语句即可修改,完整的解释说明了所需内容,提供了学习解决方案,输出方面我可以将其变成一行代码。 - sahasrara62

0

您可以使用 abs 函数。下面是一个快速示例,将其转换为用户交互形式:

import string

alphabet = string.ascii_lowercase
# a_dict = {i: letter for i, letter in enumerate(alphabet)} if you want to assign a count to x amount of keys
print('''
\t\t\tDifference calculator version 0.0.1
''')

while True:
  try:
    first = str(input('Enter first letter:> '))
    if first == 'exit':
      break
    second = str(input('Enter second letter:> '))
    if second == 'exit':
      break
    result = abs(alphabet.index(first) - alphabet.index(second))
    print('\nDistance between the letters are: ', result) # + 1 if you want to count the initial letter
    break
  except ValueError:
    print('Enter 1 Letter in each section\nType exit to quit')

0
如果你真的想要,你可以在一个一行式列表推导中完成这个任务,只需要定义字母表,获取每个字母的索引并将其与前面字母的索引进行比较。
alph = 'abcdefghijklmnopqrstuvwxyz'
source = 'abc'.lower() #add the lower just to make sure all the letters are in the predefined alph

[abs(alph.index(source[i]) - alph.index(source[i-1])) for i in range(len(source)) if i != 0]

输出:

[1, 1]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接