簡體   English   中英

遍歷字符串並打印字符之間的距離

[英]Iterate through string and print distance between characters

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]

不就是這么簡單嗎:

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
>>> 

它實際上適用於任何字符集,無論是什么情況或 class:

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
>>> 

您可以使用列表理解,通過使用ordascii轉換為intabs function

[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
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))

output

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

視覺解釋

    'a' 'b' 'c'
'a'  0   1   2
'b'  1   0   1
'c'  2   1   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')

如果您真的想通過定義字母表、獲取每個字母的索引並將其與之前字母的索引進行比較,您可以在單行列表理解中執行此操作:

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]

output:

[1, 1]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM