嗨,伙计们,我刚学会用python编写程序,有一次我被卡住了。我希望你们能解释/帮忙。 提前谢谢。在
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
,列表中的所有元素都将被删除,直到剩下一个元素为止。我不知道为什么这是个例外。在
您只需使用set从列表中删除重复项:
而不是这样做
^{pr2}$您在浏览列表时正在修改列表,因此出现错误。在
您可以使用
sests
:编辑: 考虑一下这个:
^{pr2}$当你移除}可能会失去它的位置。如果要浏览列表,必须复制并浏览该副本:
x
时,动物会发生变化,因此{相关问题 更多 >
编程相关推荐