【问题标题】:Pair strings with numbers with Python 3 [duplicate]使用 Python 3 将字符串与数字配对 [重复]
【发布时间】:2021-08-11 20:17:32
【问题描述】:

例如,如果我想将英文字母表中的每个字母与一个数字配对作为字典的位置,我将如何做到这一点而不必每次都像这样创建一个新字典:

alphabet = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10, 'k': 11, 'l': 12, 'm': 13, 'n': 14, 'o': 15, 'p': 16, 'q': 17, 'r': 18, 's': 19, 't': 20, 'u': 21, 'v': 22, 'w': 23, 'x': 24, 'y': 25, 'z': 26}

【问题讨论】:

  • 你所拥有的有什么问题?你只需要写一次。
  • 过去我也不得不制作很长的字典,我已经厌倦了总是这样做。

标签: python python-3.x dictionary


【解决方案1】:

在我的脑海中,这里有几种不同的方法(绝不是详尽的):

from string import ascii_lowercase as alphabet
from itertools import count

mapping = dict(zip(alphabet, count(start=1)))
print(mapping)

或者:

from string import ascii_lowercase as alphabet

mapping = {key: value for value, key in enumerate(alphabet, start=1)}
print(mapping)

或者:

from string import ascii_lowercase as alphabet

mapping = {char: ord(char)-ord('a')+1 for char in alphabet}
print(mapping)

输出:

{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10, 'k': 11, 'l': 12, 'm': 13, 'n': 14, 'o': 15, 'p': 16, 'q': 17, 'r': 18, 's': 19, 't': 20, 'u': 21, 'v': 22, 'w': 23, 'x': 24, 'y': 25, 'z': 26}
>>> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-08
    • 1970-01-01
    • 1970-01-01
    • 2017-07-22
    • 2014-11-27
    • 1970-01-01
    • 2016-10-12
    • 2010-09-12
    相关资源
    最近更新 更多