繁体   English   中英

将数字列表转换为字符

[英]Convert list of numbers to characters

我需要将数字列表转换为相应字符的列表。 我尝试使用chr()函数,例如:

numlist= [122, 324, 111, 789, 111]
chr(numlist)

我遇到的问题是chr()函数只能采用一个参数,并且不能将数字列表转换为字母列表。 我怎样才能做到这一点?

您需要遍历numlist并转换每个项目,以创建一个新列表:

characters = [chr(n) for n in numlist]   # Use unichr instead in Python 2.
# ['z', 'ń', 'o', '̕', 'o']

python3尝试map功能

In [5]: list(map(chr,numlist))
Out[5]: ['z', 'ń', 'o', '̕', 'o']

for chr参数必须在0到255之间,因为char仅处理ASCII,即8位,2 ^ 8-> 256,大于255,应在python 2.x中使用unichr

>>> [ unichr(x) for x in numlist ]
[u'z', u'\u0144', u'o', u'\u0315', u'o']

如果您应用chr大于255,则将出现ValueError

>>> chr(256)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: chr() arg not in range(256)

在python 3x中:

[ chr(x) for x in numlist ]
['z', 'ń', 'o', '̕', 'o']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM