嗨,大家好,我只是學習在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