簡體   English   中英

在 python 中,如何將不同長度數字的列表轉換為相同 ascii 字符的列表?

[英]In python, how would I convert a list of different length numbers to a list the same ascii characters?

我有一個數字列表:

a = [2, 2, 30, 1, 30, 6, 3, 30, 0, 9, 4, 30, 1, 30, 1, 29]

我正在嘗試將列表從整數轉換為相同數字的 ascii 字符,然后再將它們轉換為十六進制。 當有些數字超過一位數時,我在弄清楚如何轉換整個列表時遇到了麻煩。

我努力了:

a = [2, 2, 30, 1, 30, 6, 3, 30, 0, 9, 4, 30, 1, 30, 1, 29]
b = f'0x{ord(str(a)):x}'  
c = int(b, base=16)

拋出錯誤: ord() expected a character, but string of length 2 found.

它的一個變體:

a = [2, 2, 30, 1, 30, 6, 3, 30, 0, 9, 4, 30, 1, 30, 1, 29]
separated_digits = [int(digit) for number in a for digit in str(number)]
ascii_chars_hexed = [f'0x{ord(str(digit)):x}' for digit in separated_digits]

如果我將 a 中的數字拆分為單個數字,則可以工作,但我需要兩位數字的字符 output 基於 2 個數字而不是每個數字。

我期待它到 output:

[0x32, 0x32, 0x1e, 0x31, 0x1e, 0x36, 0x33, 0x1e, 0x30, 0x39, 0x34, 0x1e, 0x31, 0x1e, 0x31, 0x1d]`

有什么想法嗎?

這是一種奇怪的數據格式,但以下內容可以滿足您的需求。 將單個數字轉換為字符串並獲取其 ASCII 值。 例如,將字符串中“2”的 ASCII 值存儲為 integer 50 會更有意義。

a = [2, 2, 30, 1, 30, 6, 3, 30, 0, 9, 4, 30, 1, 30, 1, 29]
print([f'{ord(str(n)) if n < 10 else n:#x}' for n in a])

Output:

['0x32', '0x32', '0x1e', '0x31', '0x1e', '0x36', '0x33', '0x1e', '0x30', '0x39', '0x34', '0x1e', '0x31', '0x1e', '0x31', '0x1d']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM