안녕하세요, 저는 방금 파이썬으로 프로그램을 작성하는 것을 배우고 있었고 한 지점에서 멈추었습니다. 너희들이 설명하고 도와 줄 수 있기를 바랐다. 미리 감사드립니다. 나는 동물을 인쇄 할 때python list.remove() function error
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
Hey @Joe 아직 세트에 대해 알지 못했습니다. 그래서 나는 내가 배운 것을 사용하는 것만 허용됩니다! 반복하는 동안 목록을 변경하려면 위험합니까? – Newbie
반복, 일명 각 요소를 살펴 보겠습니다. for 루프와 while 루프를 사용하여'animals'리스트를 두 번하고 있습니다. 당신이 반복하고있는리스트를 수정하려고한다면 (당신이하는 것처럼), 파이썬은 버그를 빠뜨릴 수있다. 그것이 당신이보고있는 것입니다. 세트를 사용할 수 없다면, 내가 제안한 것을 사용하여 반복 할 것을 제안합니다.리스트 자체 대신 소프트 카피를 반복합니다. – Joe