简体   繁体   English

打印带有十六进制元素的 Python 列表

[英]Printing a Python list with hex elements

I have this list:我有这个清单:

a_list = [0x00, 0x00, 0x00, 0x00]

When I print it, I get:当我打印它时,我得到:

print a_list
[0, 0, 0, 0]

But I want: [0x0, 0x0, 0x0, 0x0] or [0x00, 0x00, 0x00, 0x00] , it doesn't matter for now.但我想要: [0x0, 0x0, 0x0, 0x0][0x00, 0x00, 0x00, 0x00] ,现在没关系。

I've tried to create a function such as:我尝试创建一个函数,例如:

def hex_print(the_list):
     string = '['
     for element in the_list:
         if(the_list.index(element) < len(the_list)):
             print(str(the_list.index(element)))
             string = string + hex(element) + ', '
         else:
             print(str(the_list.index(element)))
             string = string + hex(element) + ']'
     print string

But every time the printed message is:但每次打印的消息是:

[0x0, 0x0, 0x0, 0x0,

I think that the_list.index(element) always returns the first occurrence of element in the_list and not the actual position of the element.我认为 the_list.index(element) 总是返回 the_list 中元素的第一次出现,而不是元素的实际位置。 Is there a way where I can get the actual position of the element?有没有办法获得元素的实际位置?

>>> a_list = range(4)
>>> print '[{}]'.format(', '.join(hex(x) for x in a_list))
[0x0, 0x1, 0x2, 0x3]

This has the advantage of not putting quotes around all the elements, so it produces a valid literal for a list of numbers.这样做的优点是不需要在所有元素周围加上引号,因此它会为数字列表生成一个有效的文字。

Try the following:请尝试以下操作:

print [hex(x) for x in a_list]

The output shall be something like: http://codepad.org/56Vtgofl输出应类似于: http : //codepad.org/56Vtgofl

print [hex(no) for no in a_list]

hex函数将数字转换为其十六进制表示。

对于python3,使用以下代码:

print([hex(x) for x in a_list])

If you want zero padding:如果你想要零填充:

", ".join("0x{:04x}".format(num) for num in a_list)

The "0x{:04x}" puts the "0x" in front of the number. “0x{:04x}”将“0x”放在数字前面。 The "{:04x}" part pads zeros to 4 places, printing the number in hex. "{:04x}" 部分将零填充到 4 位,以十六进制打印数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM