首页 > 解决方案 > python:执行“ord”以获取字符串列表中每个字符的ascii代码

问题描述

我有一个字符串列表,我想获取每个字符串中每个字符的 ascii 代码。我正在寻找使用列表理解在一行中完成所有操作。但是,我无法使语法正常工作。

获取单个单词的代码可以正常工作:

in:[ord(x) for x in 'hello']
out:[104, 101, 108, 108, 111]

显然,列表推导可以处理从字符串列表中返回一个字符串:

in:[salutation for salutation in ['hello', 'goodbye']] 
out:['hello', 'goodbye']

但嵌套这些不起作用:

in:[ord(x) for x in [salutation for salutation in ['hello', 'goodbye']]]
out:Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <listcomp>
TypeError: ord() expected a character, but string of length 5 found

如何正确嵌套列表理解,以便内部部分返回一个字符串,然后外部部分可以逐个字符地解释?

标签: pythonlist-comprehensionord

解决方案


推荐阅读