Python:将列表中的字符串值更改为 ascii 值

标签 python string list append ascii

我正在尝试将字符串中的字符转换为单独的 ascii 值。我似乎无法让每个单独的字符都变成其相对的 ascii 值。

例如,如果变量 words 的值为 ["hello", "world"],在运行完成的代码后,列表 ascii 的值为:

[104, 101, 108, 108, 111, 119, 111, 114, 108, 100]

到目前为止我有:

words = ["hello", "world"]
ascii = []
for x in words:
    ascii.append(ord(x))

打印它返回一个错误,因为 ord 期望一个字符但得到一个字符串。有谁知道我如何解决这个问题以返回每个字母的 ascii 值?谢谢

最佳答案

将单词视为一个长字符串(例如,使用嵌套的 list-comp):

ascii = [ord(ch) for word in words for ch in word]
# [104, 101, 108, 108, 111, 119, 111, 114, 108, 100]

相当于:

ascii = []
for word in words:
    for ch in word:
        ascii.append(ord(ch))

如果你想把它们作为单独的词来做,那么你改变你的列表组合:

ascii = [[ord(ch) for ch in word] for word in words]
# [[104, 101, 108, 108, 111], [119, 111, 114, 108, 100]]

关于Python:将列表中的字符串值更改为 ascii 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25783460/

相关文章:

python - TensorFlow 批归一化实现之间有什么区别?

python - 在 Python 中从文件中读取字典的书面列表

c - 遍历C字符串: get the last word of a string

java - 数字解析库

java - 修复从 Object 到 ComboBox<String> javafx 的未检查强制转换

html - 形式低于所有其他李的李元素

python - 我在使用 "in range"显示 Python 列表时遇到问题

python - Python opencv和dicom文件

python - Skype4Py:无法授权传入的好友请求

python - 用基于字典的条目数组替换 Pandas DataFrame 列中的字符串