【问题标题】:Python: changing string values in lists into ascii valuesPython:将列表中的字符串值更改为 ascii 值
【发布时间】:2014-11-05 04:00:54
【问题描述】:

我正在尝试将字符串中的字符转换为单独的 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))

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

【问题讨论】:

    标签: python string list append ascii


    【解决方案1】:

    您的循环遍历words 列表,该列表是string 的列表。现在,ord 是一个函数,它将返回单字符字符串的整数序号。所以你还需要迭代字符串的字符。

    words = ["hello", "world"]
    ascii = []
    for word in words:
        ascii.extend(ord(ch) for ch in word)
    

    print ascii会给你,

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

    【讨论】:

      【解决方案2】:

      将单词视为一个长字符串(例如使用嵌套列表组合):

      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))
      

      如果你想将它们作为单独的词来做,那么你改变你的 list-comp:

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

      【讨论】:

      • 如果我想将 ascii 变量打印为两个单独的列表怎么办?例如[[104, 101, 108, 108, 111], [119, 111, 114, 108, 100]]
      猜你喜欢
      • 2010-09-15
      • 2012-01-17
      • 2019-11-23
      • 2020-05-18
      • 1970-01-01
      • 1970-01-01
      • 2021-11-14
      • 1970-01-01
      相关资源
      最近更新 更多