【发布时间】:2014-08-05 04:31:49
【问题描述】:
这里是 Python 初学者。我有一大组数据,从 16 位整数字符串“1,2,3,4,5”开始,最终需要变成字节对齐的二进制文件。
目前我正在使用以下内容:
#helper function
def unintlist2hex(list_input):
for current in range(len(list_input)):
list_input[current] = "%04X"%(int(list_input[current]))
return list_input
#where helper gets called in main code
for rows in dataset:
row_list = rows.text.split(",")
f_out.write(binascii.unhexlify("".join(unintlist2hex(row_list))))
但是对于我有限的数据测试大小(大约 300,000 个整数),这运行起来相当慢。我怎样才能加快速度?我分析了代码,大部分周期都花在了unintlist2hex()
请注意,我很难使用hex() 和bin(),因为它们倾向于截断前导零。
【问题讨论】:
-
我认为您不了解数据的工作原理。您正在使用 characters 为“0”和“1”创建字符串。这与在 byte 中设置 0 和 1 bits不相同。
-
@KarlKnechtel 我正试图真正反思您在这里所说的内容,但没有抓住您的意思。设置 0x0 不等于创建 0000 字节吗?您的评论是否针对“%04X”十六进制转换?
标签: python performance python-2.7 type-conversion