我对编码是全新的,我正在进行的项目将用户在地球上的重量转换为他们在太阳系不同行星上的重量。我想就如何使输出保持我在字典中输入元素的顺序提出一些建议
请原谅我的无知,因为我正在努力自学,我刚刚开始学习Python。任何指导都将不胜感激
earthWeight = float(input("How much do you weigh (in lbs)?: "))
#user's weight is calculated based on the planet.
sunWeight = earthWeight * 27.01
mercuryWeight = earthWeight * .38
venusWeight = earthWeight * .91
moonWeight = earthWeight * .166
marsWeight = earthWeight * .38
jupiterWeight = earthWeight * 2.34
saturnWeight = earthWeight * 1.06
uranusWeight = earthWeight * .92
neptuneWeight = earthWeight * 1.19
plutoWeight = earthWeight * .06
celestialWeight = {
'Weight on Sun: ' : sunWeight,
'Weight on Mercury: ' : mercuryWeight,
'Weight on Venus: ' : venusWeight,
'Weight on Moon: ' : moonWeight,
'Weight on Mars: ' : marsWeight,
'Weight on Jupiter: ' : jupiterWeight,
'Weight on Saturn: ' : saturnWeight,
'Weight on Uranus: ' : uranusWeight,
'Weight on Neptune: ' : neptuneWeight,
'Weight on Pluto: ' : plutoWeight}
for key, value in sorted(list(celestialWeight.items())):
print(key, value)
这取决于你所说的“顺序”是什么意思:
将按照您编写它们的顺序输出它们:
当
将按字母顺序输出它们:
如果要更改后验顺序,则可以这样做:
它给出了一个倒排的列表:
与其他数据集合(列表、元组)相比,字典不使用索引,但是它们在字典中添加元素时保持元素的顺序
您当前获得与预期不同结果的原因是您正在应用以下内容:
函数的作用是:返回一个由(key,pair)组成的元组,然后将它转换成一个列表,然后根据ASCII值对它进行排序(因为我们所说的键是字符串)
您需要做的只是:
您正在对词典进行排序,然后再打印。如果希望以插入顺序输出,请将
sorted(list(celestialWeight.items()))
更改为list(celestialWeight.items())
。此外,我认为没有必要将这些项目转换为列表,因为它们已经是可编辑的了——这只会引入不必要的开销。你甚至可以只做celestialWeight.items()
相关问题 更多 >
编程相关推荐