Skip to main content
 首页 » 编程设计

Python:For 循环不会完成

2025年05月04日19leader

在开始之前,我只想说我真的是编程新手,所以请不要杀了我。

作为练习,我编写了一个脚本,该脚本应该从 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) 都不起作用。我做错了什么?

请您参考如下方法:

您的第一个循环尝试遍历 hexdata,同时使用 hexdata.pop() 从列表中提取值。只需将其更改为:

for next_one in hexdata: 
    decimal = int(next_one, 16) 
    print "Converting: ", next_one, "Converted:", decimal 
    dec_data.append(decimal)