为什么Python中的这个字典只存储最后的输入?

2024-10-04 03:22:25 发布

您现在位置:Python中文网/ 问答频道 /正文

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,但结果是一样的。你知道吗


Tags: thefrompackageinputdatarawpackcapacity
1条回答
网友
1楼 · 发布于 2024-10-04 03:22:25

在循环的每次迭代中,都将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

那应该会解决的。你知道吗

相关问题 更多 >