gpt4 book ai didi

python - 写这个表达式的有效方法 : English alphabets dictionary

转载 作者:太空宇宙 更新时间:2023-11-04 07:25:15 26 4
gpt4 key购买 nike

什么是实现此表达式的有效且正确的方法?

{'a': 1, 'b': 2 ... 'z': 26}

我试过:

x = dict(zip(chr(range(ASCII of A, ASCII of Z)))

是这样的吗?但是我想不出正确的表达方式。

最佳答案

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

enumerate(lowercase) 返回此序列 (0, 'a'), (1, 'b'), (2, 'c'),...

通过添加可选参数,枚举从 1 而不是 0 开始

enumerate(lowercase, 1) 返回此序列 (1, 'a'), (2, 'b'), (3, 'c'),...

python 2.6之前的版本不支持可选参数,所以你可以这样写

>>> dict((j,i+1) for i,j in enumerate(lowercase)) 

关于python - 写这个表达式的有效方法 : English alphabets dictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4112189/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com