2014-04-03 36 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