使用Python将数字转换为对应的字母

33

我想知道是否有可能将数字转换为它们对应的字母值。所以

1 -> a
2 -> b

我原计划编写一个程序,它可以列出用户指定长度的所有字母组合。

但我不知道如何完成这一部分!如果有帮助,将万分感谢。


1a是如何对应的? - thefourtheye
3
如果数字是27,输出应该是什么? - thefourtheye
7个回答

57

大写字母:

chr(ord('@')+number)

1 -> A

2 -> B

...

小写字母:

chr(ord('`')+number)

1 -> a

2 -> b

...


1
谢谢!对于任何其他人的pandas映射,我做了这个:df['number_col'] = df['number_col'].astype(int).apply(lambda x: chr(ord('`')+x)) - kevin_theinfinityfund

17
import string
for x, y in zip(range(1, 27), string.ascii_lowercase):
    print(x, y)
或者
import string
for x, y in enumerate(string.ascii_lowercase, 1):
    print(x, y)
或者
for x, y in ((x + 1, chr(ord('a') + x)) for x in range(26)):
    print(x, y)

以上所有解决方案均输出英文字母小写形式以及它们在英文字母表中的位置:

1 a
...
26 z
您可以创建一个字典,通过键(位置)轻松访问字母(值)。例如:

You'd create a dictionary to access letters (values) by their position (keys) easily. For example:

import string
d = dict(enumerate(string.ascii_lowercase, 1))
print(d[3]) # c

9
你可以使用 chr() 将数字转换为字符,但需要以更高的起始点开始,因为ASCII表中有其他几个字符在先。
使用 ord('a') - 1 作为起始点:
start = ord('a') - 1
a = chr(start + 1)

示例:

>>> start = ord('a') - 1
>>> a = chr(start + 1)
>>> a
'a'

另一种选择是使用 string.ascii_lowercase 常量 作为一个序列,但您需要从 开始索引:
import string

a = string.ascii_lowercase[0]

8
什么是字典?
>>> import string
>>> num2alpha = dict(zip(range(1, 27), string.ascii_lowercase))
>>> num2alpha[2]
b
>>> num2alpha[25]
y

但是不要超过26:
>>> num2alpha[27]
KeyError: 27

但如果你要找到给定长度的所有字母组合:
>>> import string
>>> from itertools import combinations_with_replacement as cwr
>>> alphabet = string.ascii_lowercase
>>> length = 2
>>> ["".join(comb) for comb in cwr(alphabet, length)]
['aa', 'ab', ..., 'zz']

6

尝试使用字典和递归:

def Getletterfromindex(self, num):
    #produces a string from numbers so

    #1->a
    #2->b
    #26->z
    #27->aa
    #28->ab
    #52->az
    #53->ba
    #54->bb

    num2alphadict = dict(zip(range(1, 27), string.ascii_lowercase))
    outval = ""
    numloops = (num-1) //26

    if numloops > 0:
        outval = outval + self.Getletterfromindex(numloops)

    remainder = num % 26
    if remainder > 0:
        outval = outval + num2alphadict[remainder]
    else:
        outval = outval + "z"
    return outval

1
这里有一个快速的解决方案:
# assumes Python 2.7
OFFSET = ord("a") - 1

def letter(num):
    return chr(num + OFFSET)

def letters_sum_to(total):
    for i in xrange(1, min(total, 27)):
        for rem in letters_sum_to(total - i):
            yield [letter(i)] + rem
    if total <= 26:
        yield [letter(total)]

def main():
    for letters in letters_sum_to(8):
        print("".join(letters))

if __name__=="__main__":
    main()

which produces

aaaaaaaa
aaaaaab
aaaaaba
aaaaac
aaaabaa
aaaabb
aaaaca
aaaad
aaabaaa
# etc

请注意,总和为N的解决方案数量为2 **(N-1)。

1
for i in range(0, 100):
     mul = 1
     n   = i
     if n >= 26:
         n   = n-26
         mul = 2
     print chr(65+n)*mul

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接