我有一个计划,它应该在一年中的每个月得到多少雪,将其存储在字典中并以正确的顺序打印所有数据。我还需要打印全年的雪总量。
这是我到目前为止所做的:
def main():
M=['January', 'February', 'March','April', 'May', 'June', 'July', 'August','September', 'October', 'November', 'December']
dic = {}
for i in range(0, len(M)):
theKeys = list(dic.items())
theKeys.sort()
inpt = int(input("How much did it snow in " + str(M[i]) + " ?:"))
dic[str(M[i])] = inpt
theKeys = list(dic.items())
theKeys.sort()
print(dic)
main()
此程序以正确的顺序询问用户雪。然而,当它打印出所有东西时,这就是我得到的:
How much did it snow in January ?:1
How much did it snow in February ?:2
How much did it snow in March ?:3
How much did it snow in April ?:4
How much did it snow in May ?:5
How much did it snow in June ?:6
How much did it snow in July ?:7
How much did it snow in August ?:8
How much did it snow in September ?:9
How much did it snow in October ?:10
How much did it snow in November ?:11
How much did it snow in December ?:12
{'June': 6, 'July': 7, 'January': 1, 'December': 12, 'March': 3, 'October': 10, 'September': 9, 'May': 5, 'August': 8, 'February': 2, 'April': 4, 'November': 11}
另外,我可以使用什么功能来打印总雪量?和()? 我的书并没有很多关于词典的信息。对不起,如果这是一个非常愚蠢的问题。
答案 0 :(得分:0)
执行theKeys.sort()
时,您只会对列表theKeys
进行排序,而不是真正的键。
要正确打印,您可以使用模块collections
中的OrderedDict。
OrderedDict是一个记住首次插入密钥的顺序的字典。
排序将按字母顺序排序:
for k in theKeys:
... print k,dic[k]
...
April 4
August 8
December 12
February 2
January 1
July 7
June 6
March 3
May 5
November 11
October 10
September 9
关于总和,请使用dic.values()
>>> print sum(i for i in dic.values())
78
答案 1 :(得分:0)
你有一些额外的行,如果你想按照输入的方式对字典输出进行排序,你需要使用OrderedDict
>>> from collections import OrderedDict as od
>>> def myfunc():
M=['January', 'February', 'March','April', 'May', 'June', 'July', 'August','September', 'October', 'November', 'December']
weather = od() #defining an ordered dictionary
for i in range(0, len(M)):
#theKeys = list(weather.items()) # you are not using this line
#theKeys.sort() # you are not using this one
inpt = int(input("How much did it snow in " + str(M[i]) + " ?:"))
weather[str(M[i])] = inpt
#theKeys = list(weather.items()) # this one is not used
print "total snow during the year was ", sum(weather.values())
print(weather)
行总和(weather.values())导致使用天气词典中的值构建列表,然后将该值列表相加
weather = od()使用名称weather
初始化OrderedDictionary>>> myfunc()
How much did it snow in January ?:1
How much did it snow in February ?:1
How much did it snow in March ?:1
How much did it snow in April ?:1
How much did it snow in May ?:1
How much did it snow in June ?:1
How much did it snow in July ?:1
How much did it snow in August ?:1
How much did it snow in September ?:1
How much did it snow in October ?:1
How much did it snow in November ?:1
How much did it snow in December ?:1
total snow during the year was 12
OrderedDict([('January', 1), ('February', 1), ('March', 1), ('April', 1), ('May', 1), ('June', 1), ('July', 1), ('August', 1), ('September', 1), ('October', 1), ('November', 1), ('December', 1)])
答案 2 :(得分:0)
字典无序。在你的情况下,这不是一个问题,因为你有正确的顺序,只有一组已知和有限的键和值。试试这个:
>>> print(", ".join("{}: {}".format(m, dic[m]) for m in M))
January: 1, February: 2, March: 3, April: 4, May: 5, June: 6, July: 7, August: 8, September: 9, October: 10, November: 11, December: 12
你也做了许多你不应该做的事情,比如当你有一个非字母顺序的要求时,你可以对字典的键进行排序。您还要将字符串转换为字符串并按索引访问元素,这是不必要的。这是一个简化版本:
>>> def snow_fall():
... months = ['January', 'February', 'March','April', 'May', 'June', 'July', 'August','September', 'October', 'November', 'December']
... snow_fall = {}
... for month in months:
... snow_fall[month] = input("How much did it snow in {}? ".format(month))
... print(", ".join("{}: {}".format(m, snow_fall[m]) for m in months))
... print("Total snowfall: {}".format(sum(snow_fall.values())))
...
>>>
一些解释:
Pythons for-loop与大多数语言不同。它更像是for-each-loop。您可以迭代一系列元素,它将为您提供该元素。如果您绝对需要索引,则使用enumerate。因此,for month in months
会为您提供January, February ..
按照上面显示的正确顺序打印
通过将字典值相加来打印总降雪量。
演示:
>>> snow_fall()
How much did it snow in January? 10
How much did it snow in February? 5
How much did it snow in March? 18
How much did it snow in April? 3
How much did it snow in May? 0
How much did it snow in June? 0
How much did it snow in July? 0
How much did it snow in August? 0
How much did it snow in September? 20
How much did it snow in October? 30
How much did it snow in November? 80
How much did it snow in December? 120
January: 10, February: 5, March: 18, April: 3, May: 0, June: 0, July: 0, August: 0, September: 20, October: 30, November: 80, December: 120
Total snowfall: 286
答案 3 :(得分:0)
首先,字典或映射类型没有任何关于其键的顺序。这是由于其底层结构中的哈希算法。
但Python使用其标准库来解决问题。查看文档:{{3}}
此外,您无需以任何方式摆弄键或月份列表,这是使用OrderedDict自动完成的。
来自集合导入OrderedDict
def main():
"""
Query the amount of snow in each month of a specific year, store it and print
the amounts. Calculates the sum of all amounts and print it.
"""
m = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August',
'September', 'October', 'November', 'December']
dic = OrderedDict()
for month in m:
dic[month] = int(input("How much did it snow in " + month + "? :"))
# prints the object-representation of the OrderedDict
print(dic)
# a slightly better output
from pprint import pprint
pprint(dic)
# calculate the sum
print(sum(dic.values()))
if __name__ == '__main__':
main()
另一个小技巧:代码风格的好讲座是http://docs.python.org/3.3/library/collections.html#collections.OrderedDict 这并不意味着上述代码完全符合:)