我试图找出如何生成一个列表(对于每个字符串),一个ASCII值列表,表示每个字符串中的字符。
EG。改变"你好","世界"所以它看起来像:
[[104, 101, 108, 108, 111], [119, 111, 114, 108, 100]]
到目前为止我的代码:
words = ["hello", "world"]
ascii = []
for word in words:
ascii_word = []
for char in word:
ascii_word.append(ord(char))
ascii.append(ord(char))
print ascii_word, ascii
我知道它不起作用,但我正在努力让它正常运作。任何帮助将非常感激。三江源
答案 0 :(得分:1)
一种方法是使用嵌套的list comprehension:
>>> [[ord(c) for c in w] for w in ['hello', 'world']]
[[104, 101, 108, 108, 111], [119, 111, 114, 108, 100]]
这只是编写以下代码的简洁方法:
outerlist = []
for w in ['hello', 'world']:
innerlist = []
for c in w:
innerlist.append(ord(c))
outerlist.append(innerlist)
答案 1 :(得分:1)
你很亲密:
words = ["hello", "world"]
ascii = []
for word in words:
ascii_word = []
for char in word:
ascii_word.append(ord(char))
ascii.append(ascii_word) # Change this line
print ascii # and only print this.
但请查看list comprehensions和@ Shashank的代码。