2012-12-22 7 views
0
while (lines < travels + 1): 
    data = lines + 1 
    startFrom = raw_input ('The package travels from: ') 
    startFrom = str(startFrom) 
    arriveIn = raw_input ('The package arrives to: ') 
    arriveIn = str(arriveIn) 
    pack = raw_input('Number of packages: ') 
    pack = int(pack) 
    print startFrom, '--->', arriveTo, ': ', pack 
    capacity = {} 
    if capacity.has_key(startFrom): 
     capacity[startFrom] = capacity[startFrom] + pack 
    else: 
     capacity[startFrom] = pack 
print capacity 

마지막으로 지정된 입력 만 인쇄하고 저장하며 값을 증가시키지 않고 새 데이터를 사전에 추가하지 않습니다. 나도 defaultdic로 시도했지만 결과는 같았다.왜 파이썬의이 사전은 마지막 입력 만 저장합니까?

+1

'capacity = {}'이 (가) 범인입니다. 또한'has_key'를 사용하지 마십시오. 더 이상 사용되지 않습니다. 'startFrom in capacity'을 사용하십시오. –

답변

3

capacity을 루프를 통해 반복 할 때마다 dict으로 재설정합니다.

capacity = {} #Create it before the loop and use this through out the below loop. 
while (lines < travels + 1): 
data = lines + 1 
startFrom = raw_input ('The package travels from: ') 
startFrom = str(startFrom) 
arriveIn = raw_input ('The package arrives to: ') 
arriveIn = str(arriveIn) 
pack = raw_input('Number of packages: ') 
pack = int(pack) 
print startFrom, '--->', arriveTo, ': ', pack 
if startFrom in capacity:#Style change and more pythonic 
    capacity[startFrom] = capacity[startFrom] + pack 
else: 
    capacity[startFrom] = pack 
print capacity 

해결해야합니다.

관련 문제