当给出整数时,我如何创建一个新的列表,并且必须返回十六进制



给定以下列表:list = [2,10,10,10,4,5]

如何编写返回输出的函数:output = 210AA:45

到目前为止,我一直在处理这段代码,但不知道还需要添加什么,这样,一旦重复了10到15之间的数字,就可以像输出中那样以十六进制形式返回重复的数字

def int_to_string(data): 
string = ""
for i in data: 
hexadecimal = hex(i)
string += hexadecimal[2:]
string[0] = 15
return string

使用列表[]而不是字符串""字符串是不可变的,不支持索引查找和赋值。附加十六进制val,然后根据需要编辑第一个索引以获得结果并与重新运行加入列表''.join(#ur_lst)

描述十进制和十六进制之间映射的字典可以增加可读性。

备注:不要隐藏构建函数的名称,在这种情况下为list。有关完整列表,请参阅文档。

lst = [2,10,10,10,4,5,13,15,0] # <- new testing list
# dictionary for conversion
num2hex = {i: str(i) for i in range(10)}
num2hex.update(zip(range(10, 16), "ABCDEF")) 
# conversion list -> str
res = ''
consecutve_hex, is_last_hex = 0, False
for d in lst:
if 10 <= d <= 15:
consecutive_hex += 1
is_last_hex = False
if consecutive_hex > 1:
res += num2hex[d]
else:
res += str(d)
else:
if not is_last_hex:
if res:
res += ':'
consecutive_hex = 0 
is_last_hex = True
res += str(d)
print(res)
#210AA:4513F:0

最新更新