【问题标题】:Map character string to alphabetical numeric (using dictionary)将字符串映射到字母数字(使用字典)
【发布时间】:2021-01-12 00:50:10
【问题描述】:

使用字典...

import string
alphabet = string.ascii_lowercase
alphabet1 = string.ascii_uppercase

a = "This is some string"


b = dict()
for i in range(len(alphabet)):
    b[i] = alphabet[i]
    
c = dict()
for i in range(len(alphabet1)):
    c[i] = alphabet1[i]

到了一半...不知道如何使用 for/while 迭代循环来输出与“This is some string”相关联的数字序列;例如,[19, 7, 8, ...]

问候。

【问题讨论】:

标签: python python-3.6


【解决方案1】:

您可以通过从enumerate(string.ascii_letters) 交换键值对来简化它,然后通过访问结果字典中该键的值来获取索引:

from string import ascii_letters

# reverse key, value pairs form ascii_letters for accessibility later
chars = {value: index for index, value in enumerate(ascii_letters)}

def index_string(text):
    # access the index for each key if it exists in chars (ascii_letters) and return it as a list
    return [chars[char] for char in text if char in chars]

print(index_string("This is some string"))

输出:

[45, 7, 8, 18, 8, 18, 18, 14, 12, 4, 18, 19, 17, 8, 13, 6]

作为参考,chars 字典如下所示:

{'a': 0,
 'b': 1,
 'c': 2,
 'd': 3,
 'e': 4,
 'f': 5,
 'g': 6,
 'h': 7,
 'i': 8,
 'j': 9,
 'k': 10,
 'l': 11,
 'm': 12,
 'n': 13,
 'o': 14,
 'p': 15,
 'q': 16,
 'r': 17,
 's': 18,
 't': 19,
 'u': 20,
 'v': 21,
 'w': 22,
 'x': 23,
 'y': 24,
 'z': 25,
 'A': 26,
 'B': 27,
 'C': 28,
 'D': 29,
 'E': 30,
 'F': 31,
 'G': 32,
 'H': 33,
 'I': 34,
 'J': 35,
 'K': 36,
 'L': 37,
 'M': 38,
 'N': 39,
 'O': 40,
 'P': 41,
 'Q': 42,
 'R': 43,
 'S': 44,
 'T': 45,
 'U': 46,
 'V': 47,
 'W': 48,
 'X': 49,
 'Y': 50,
 'Z': 51}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-18
    • 1970-01-01
    • 1970-01-01
    • 2018-10-18
    • 2021-07-12
    • 2021-05-09
    • 2017-01-31
    相关资源
    最近更新 更多