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 但结果是一样的。

4

1 回答 1

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

那应该解决它。

于 2012-12-22T08:34:35.667 回答