简体   繁体   English

在 python 中,如何将不同长度数字的列表转换为相同 ascii 字符的列表?

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

I have a list of numbers:我有一个数字列表:

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

I am trying to convert the list from integers to ascii characters of the same number before converting them to hex.我正在尝试将列表从整数转换为相同数字的 ascii 字符,然后再将它们转换为十六进制。 I am running into trouble figuring out how to convert the entire list when there are some numbers with more than one digit.当有些数字超过一位数时,我在弄清楚如何转换整个列表时遇到了麻烦。

I have tried:我努力了:

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)

which throws the error: ord() expected a character, but string of length 2 found.抛出错误: ord() expected a character, but string of length 2 found.

A variation of it:它的一个变体:

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]

works if I split the numbers in a into single digits, but I need the character output of the double digit numbers to be based upon the 2 digits rather than each individually.如果我将 a 中的数字拆分为单个数字,则可以工作,但我需要两位数字的字符 output 基于 2 个数字而不是每个数字。

I am expecting it to output:我期待它到 output:

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

Any thoughts?有什么想法吗?

It's an odd data format, but the following does what you want.这是一种奇怪的数据格式,但以下内容可以满足您的需求。 Convert the single-digit numbers to a string and get their ASCII value.将单个数字转换为字符串并获取其 ASCII 值。 It would make more sense to store the ASCII value of the '2' in the string as the integer 50 to begin with, for example.例如,将字符串中“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: 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