2012-05-03 80 views
1

在我開始之前,讓我只說我對編程非常陌生,所以請不要殺了我。Python:For循環不會完成

作爲一個練習,我編寫了一個腳本,該腳本應該從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)。我究竟做錯了什麼?

+0

dec_data中出現了多少個? –

+0

'hexdata.pop(x + 1)'似乎很奇怪...... –

回答

5

您的第一個循環嘗試迭代hexdata,同時使用hexdata.pop()將值從列表中拉出。只需將其更改爲如下所示:

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

謝謝,我不知道會引起問題。 – Anteras

1

迭代列表時的原則是不要修改要迭代的列表。如果必須,您可以製作一份列表的副本以進行迭代。

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[:]

+0

我想指出''hexdata [:]'不是**深層複製(不是你需要在這裏,但它是誤導性的說它是一個)。這是一個淺拷貝。對於深層複製,您需要['copy.deepcopy()'](http://docs.python.org/library/copy.html#copy.deepcopy)。另外,即使對於淺拷貝,那麼不清楚的語法'list(hexdata)'或'copy.copy(hexdata)'會更好。 –

+0

你是對的@Lattyware,我會更新我的答案以反映這一點。 – Makoto