在我开始之前,让我先说一下,我对编程真的很陌生,所以请不要杀了我。
作为练习,我编写了一个脚本,该脚本从txt中获取十六进制数字的列表,将它们转换为十进制,并将它们写入另一个文件。这是我想出来的:
hexdata = open(raw_input("Sourcefile:")).read().split(',')
dec_data = []
print hexdata
x = -1
for i in hexdata:
next_one = hexdata.pop(x+1)
decimal = int(next_one, 16)
print "Converting: ", next_one, "Converted:", decimal
dec_data.append(decimal)
print dec_data
target = open(raw_input("Targetfile: "), 'w')
for n in dec_data:
output = str(n)
target.write(output)
target.write(",")当我运行脚本时,它没有错误地结束,但是它只转换和写入我的源文件中的前30个数字,而忽略了所有其他的数字,即使它们被加载到'hexdata‘列表中。我尝试了几种不同的方法,但始终不能处理所有的数字(48)。我做错了什么?
发布于 2012-05-04 05:31:51
您的第一个循环尝试迭代十六进制数据,同时使用hexdata.pop()从列表中提取值。只需将其更改为如下所示:
for next_one in hexdata:
decimal = int(next_one, 16)
print "Converting: ", next_one, "Converted:", decimal
dec_data.append(decimal)发布于 2012-05-04 05:34:01
迭代列表时的原则是不要修改正在迭代的列表。如果有必要,您可以复制列表以进行迭代。
for i in hexdata[:]: # this creates a shallow copy, or a slice of the entire list
next_one = hexdata.pop(x+1)
decimal = int(next_one, 16)
print "Converting: ", next_one, "Converted:", decimal
dec_data.append(decimal)您还可以使用copy.deepcopy创建深层副本,这将允许您避免hexdata[:]等浅层副本中出现的问题。
https://stackoverflow.com/questions/10439550
复制相似问题