Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将整数列表的字典打印为十六进制_Python_String_Dictionary_Format_Hex - Fatal编程技术网

Python 将整数列表的字典打印为十六进制

Python 将整数列表的字典打印为十六进制,python,string,dictionary,format,hex,Python,String,Dictionary,Format,Hex,我需要在Python2.7中将包含多个整数列表的字典格式化为十六进制 我找到了一种将字典中的整数格式化为十六进制的方法。在本例中,十六进制将起作用,而十六进制列表将不起作用 dict = { "hex": 0x12, "hexlist": [0x13, 0x14] } print("{hex:x}, {hexlist:x}".format(**dict)) () 还有一种方法可以使用以下命令将整数列表打印为十六进制: ''.join('{:02X}'.format(hex) fo

我需要在Python2.7中将包含多个整数列表的字典格式化为十六进制

我找到了一种将字典中的整数格式化为十六进制的方法。在本例中,十六进制将起作用,而十六进制列表将不起作用

dict = {
   "hex": 0x12,
   "hexlist": [0x13, 0x14]
}

print("{hex:x}, {hexlist:x}".format(**dict))
()

还有一种方法可以使用以下命令将整数列表打印为十六进制:

''.join('{:02X}'.format(hex) for hex in hexlist)
()


但我不知道如何将两者结合起来

始终可以检查变量类型:

def get_hex_representation(struct):
    str = None
    if type(struct) is list:
        str = ''.join('{:02X}'.format(hex) for hex in hexlist)
    elif type(struct) is dict:
        str = '{hex:x}, {hexlist:x}'.format(**dict)
    return str

另外,如果您的结构既不是
list
也不是
dict
,您可以抛出一个异常,而不是返回
None
,我现在就这样解决了它。检查类型的想法是关键。这个函数将输出一个元组,其中包含键和值的列表,我可以进一步处理这些键和值。这可能不是最优雅的解决方案,但目前仍适用

def getHexMsg(message):
    strVal = []
    strKey = []
    for key, value in message.items():
        strKey.append("{}: ".format(key))
        if type(value) is list:
            strVal.append(' '.join('{:02X}'.format(hex) for hex in value))
        elif type(value) is int:
            strVal.append('{:02X} '.format(value))
    return (strKey, strVal)

是的,谢谢,检查类型的想法似乎是可行的。