[英]Python: changing string values in lists into ascii values using append
[英]Python: changing string values in lists into ascii values
我正在嘗試將字符串中的字符轉換為單獨的ascii值。 我似乎無法讓每個角色都變成相對的ascii值。
例如,如果變量單詞具有值[“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))
如果你想把它們作為單獨的單詞,那么你改變你的list-comp:
ascii = [[ord(ch) for ch in word] for word in words]
# [[104, 101, 108, 108, 111], [119, 111, 114, 108, 100]]
你的循環遍歷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]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.