生成字母表的字母

时间:2015-07-28 01:42:13

标签: python dictionary

嗨所以我想以

的形式生成python字母的dict

{'a':'a', 'b':'b', 'c':'c'....}

链接here非常有用,但是当我用string.ascii.lowercase替换那里的最后一个0时,我得到了这个:

{'a': 'abcdefghijklmnopqrstuvwxyz', 'b': 'abcdefghijklmnopqrstuvwxyz', 'c': 'abcdefghijklmnopqrstuvwxyz'...}

那么,我该如何解决这个问题?

5 个答案:

答案 0 :(得分:2)

您可以尝试这种方式:

dict([(character,character) for character in string.ascii_lowercase])

或另一个:

dict(zip(string.ascii_lowercase,string.ascii_lowercase))

答案 1 :(得分:0)

characters = {}
for character in string.ascii.lowercase:
    characters[character] = character

答案 2 :(得分:0)

以下是制作转换字典的一种方法:

def shiftDict(i):
    i = i % 26
    alpha = 'abcdefghijklmnopqrstuvwxyz'
    return dict(zip(alpha,alpha[i:] + alpha[:i]))

原始问题shiftDict(0)会返回您要求的内容。 另一个例子:

>>> d = shiftDict(3)
>>> d
{'u': 'x', 'w': 'z', 'e': 'h', 'r': 'u', 'o': 'r', 'c': 'f', 'x': 'a', 'i': 'l', 'k': 'n', 't': 'w', 'h': 'k', 'j': 'm', 'b': 'e', 'l': 'o', 'y': 'b', 'f': 'i', 's': 'v', 'q': 't', 'm': 'p', 'd': 'g', 'v': 'y', 'p': 's', 'g': 'j', 'z': 'c', 'n': 'q', 'a': 'd'}

但是对于Caesar转变 - 您可能希望使用字符串translate方法。

答案 3 :(得分:0)

使用字典和范围怎么办?

>>> dict = {chr(ord('a') + i) : chr(ord('a') + i) for i in range(26)}
>>> dict
{'a': 'a', 'c': 'c', 'b': 'b', 'e': 'e', 'd': 'd', 'g': 'g', 'f': 'f', 'i': 'i', 'h': 'h', 'k': 'k', 'j': 'j', 'm': 'm', 'l': 'l', 'o': 'o', 'n': 'n', 'q': 'q', 'p': 'p', 's': 's', 'r': 'r', 'u': 'u', 't': 't', 'w': 'w', 'v': 'v', 'y': 'y', 'x': 'x', 'z': 'z'}

您可以创建通用函数

def gen_alpha_range(start, count):
    return {chr(ord(start) + i) : chr(ord(start) + i) for i in range(count)}

result = gen_alpha_range('A', 5)
print(result)

>>> {'A': 'A', 'C': 'C', 'B': 'B', 'E': 'E', 'D': 'D'}

答案 4 :(得分:0)

import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import time

# Data for plotting
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)

fig, ax = plt.subplots()
ax.plot(t, s)

ax.set(xlabel='time (s)', ylabel='voltage (mV)',
       title='About as simple as it gets, folks')
ax.grid()

plt.show()

while True:
    print('finished')
    time.sleep(1)

它将返回包含所有小写字母的列表。

相关问题