4 回答

TA貢獻1810條經驗 獲得超4個贊
您肯定需要一個字典來實現此目的,而不是將每個聲明為變量。一種簡單的方法是使用字典理解string.ascii_lowercaseas:
from string import ascii_lowercase
{v:k for k,v in enumerate(ascii_lowercase)}
# {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5...

TA貢獻1860條經驗 獲得超9個贊
這是我的兩分錢,for 循環將完成這項工作:
d = {} #empty dictionary
alpha = 'abcdefghijklmnopqrstuvwxyz'
for i in range(26):
d[alpha[i]] = i #assigns the key value as alphabets and corresponding index value from alpha string as the value for the key
print(d) #instant verification that the dictionary has been created properly

TA貢獻1796條經驗 獲得超10個贊
帶有地圖和枚舉的一行:
# given
foo = 'abcxyz'
dict(enumerate(foo))
# returns: {0: 'a', 1: 'b', 2: 'c', 3: 'x', 4: 'y', 5: 'z'}
如果你需要用字符作為字典鍵,我想到的要么是字典理解......
{letter:num for (num,letter) in enumerate(foo) }
# returns {'a': 0, 'b': 1, 'c': 2, 'z': 3, 'y': 4, 'x': 5}
...或 lambda...
dict( map(lambda x: (x[1],x[0]), enumerate(foo)) )
# returns {'a': 0, 'b': 1, 'c': 2, 'z': 3, 'y': 4, 'x': 5}
我覺得 dict 理解比 map+lambda+enumerate更具可讀性。

TA貢獻1824條經驗 獲得超8個贊
已經有與字符相關聯的數字。您可以將這些代碼點與ord()一起使用。
一個簡短的(就行而言)解決方案是:
num_of = lambda s: ord(s) - 97
一個普通的函數會更容易閱讀:
def num_of(s):
return ord(s) - 97
用法:
num_of("a") # 0
num_of("z") # 25
如果它必須是字典,您可以在不導入的情況下創建它,如下所示:
{chr(n):n-97 for n in range(ord("a"), ord("z")+1)}
添加回答
舉報