嗨,大家好,我只是学习在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
在遍历整个列表时,对列表进行变更是很危险的。快速尝试:'对于动物中的x [:]:'。尽管这是一个问题。为什么你不能使用套件呢? – Joe
嘿@Joe我还没有学过套。所以我只能用我学过的东西!迭代时危险列表变异? – Newbie
迭代,即你正在经历每个元素。你用for循环和while循环为'animals'列表做了两次。如果你试图修改你正在迭代的列表(就像你正在做的那样),Python可能(并且通常会)会出错。这就是你所看到的。如果你不能使用集合,我建议你使用我的建议迭代 - 它将遍历一个软拷贝而不是列表本身。 – Joe