2014-04-03 51 views
0

嗨,大家好,我只是學習在python中編寫程序,並被卡住了一個點。我希望你們能解釋/幫助。 在此先感謝。python list.remove()函數錯誤

items=[] 
animals=[] 
station1={} 
station2={} 
import os.path 

def main(): 
    endofprogram=False 
    try: 
     filename=input('Enter name of input file >')   
     file=open(filename,'r') 
    except IOError: 
     print('File does not exist') 
     endofprogram=True  

    if (endofprogram==False): 
     for line in file: 
      line=line.strip('\n') 
      if (len(line)!=0)and line[0]!='#': 
       (x,y,z)=line.split(':') 
       record=(x,y,z) 
       temprecord=(x,z) 
       items.append(record) 
       animals.append(x) 

       if temprecord[1]=='s1': 
        if temprecord[0] in station1: 
         station1[temprecord[0]]=station1[temprecord[0]]+1 
        else: 
         station1[temprecord[0]]=1 
       elif temprecord[1]=='s2': 
        if temprecord[0] in station2: 
         station2[temprecord[0]]=station2[temprecord[0]]+1 
        else: 
         station2[temprecord[0]]=1 
    print(animals) 
    for x in animals: 
     while animals.count(x)!=1: 
      animals.remove(x) 
    animals.sort() 

    print(animals) 


main() 

所以,當我打印動物它打印['a01', 'a02', 'a02', 'a02', 'a03', 'a04', 'a05'] 在列表中的元素,會刪除,直到一個所有被留下,除了a02。我不知道爲什麼這是一個例外。

File: 

a01:01-24-2011:s1 
a03:01-24-2011:s2 
a03:09-24-2011:s1 
a03:10-23-2011:s1 
a04:11-01-2011:s1 
a04:11-02-2011:s2 
a04:11-03-2011:s1 
a04:01-01-2011:s1 
+3

在遍歷整個列表時,對列表進行變更是很危險的。快速嘗試:'對於動物中的x [:]:'。儘管這是一個問題。爲什麼你不能使用套件呢? – Joe

+0

嘿@Joe我還沒有學過套。所以我只能用我學過的東西!迭代時危險列表變異? – Newbie

+2

迭代,即你正在經歷每個元素。你用for循環和while循環爲'animals'列表做了兩次。如果你試圖修改你正在迭代的列表(就像你正在做的那樣),Python可能(並且通常會)會出錯。這就是你所看到的。如果你不能使用集合,我建議你使用我的建議迭代 - 它將遍歷一個軟拷貝而不是列表本身。 – Joe

回答

0

你可以只使用set的目的是從列表中刪除重複項:

list(set(animals)) 

而不是做這個

for x in animals: 
    while animals.count(x)!=1: 
     animals.remove(x) 
+1

嘿。不知道這個功能。一定會讀到它!我是這樣做的,因爲它很容易,因爲它之前我用過它 – Newbie

+0

@Newbie沒問題:)你可以請現在[接受](http://meta.stackexchange.com/a/5235/203656)我的回答? –

+1

我試過這樣做。說7分鐘不能接受?我不知道爲什麼 – Newbie

0

要修改的列表中同時瀏覽它,因此錯誤。

你能爲你的問題做什麼用sests

>>> list(set(animals)) 
['a02', 'a03', 'a01', 'a04', 'a05'] 
>>> a2=list(set(animals)) 
>>> a2.sort() 
>>> a2 
['a01', 'a02', 'a03', 'a04', 'a05'] 

編輯: 考慮這個問題:

>>> animals 
['a01', 'a02', 'a02', 'a02', 'a03', 'a04', 'a05'] 
>>> for x in animals: 
... animals.remove(x) 
... 
>>> animals 
['a02', 'a02', 'a04'] 

當您刪除x,動物被改變,所以for可以失去跟蹤它在哪裏。如果您想瀏覽列表,您必須複製並瀏覽副本:

>>> animals=['a01', 'a02', 'a02', 'a02', 'a03', 'a04', 'a05'] 
>>> for x in animals[:]: 
... animals.remove(x) 
... 
>>> animals 
[] 
+0

那麼,爲什麼'ao2'和其他人正在根據代碼工作的具體錯誤?任何想法? – Newbie

+1

就像我之前說過的。引人注目。 :)僅供參考,您的第二個解決方案不起作用。一個調整是添加一個'if'條件來檢查當前元素是否在列表中多次存在。 – Joe

+0

@Newbie我已經更新了我的答案。 – fredtantini