如何用简洁的方式创建一个以字母为主的字母? [英] How to create a dict with letters as keys in a concise way?
本文介绍了如何用简洁的方式创建一个以字母为主的字母?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个这样的26个字母字母的字典:
I created an dictionary of the 26 alphabet letters like this:
aDict={
"a": 1,
"b": 2,
"c": 3,
"d": 4,
etc...
}
我试图让我的代码更好,我的问题是,
有没有更短的方法来做到这一点没有输入所有这些数字?
I'm trying make my code better and my question is, is there any shorter way to do this without typing all these numbers out?
推荐答案
您可以使用 string.ascii_lowercase
,并在这里进行词典理解。
You can use string.ascii_lowercase
and dict comprehension here.
In [4]: from string import ascii_lowercase as al
对于Python 2.7 +:
For Python 2.7+:
In [5]: dic = {x:i for i, x in enumerate(al, 1)}
对于Python 2.6或更早版本:
For Python 2.6 or earlier:
In [7]: dic = dict((y, x) for x, y in enumerate(al, 1))
这篇关于如何用简洁的方式创建一个以字母为主的字母?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文