Python当我打印所有的键、值对时,我应该如何保持它们的顺序?

2024-10-03 00:23:13 发布

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

我对编码是全新的,我正在进行的项目将用户在地球上的重量转换为他们在太阳系不同行星上的重量。我想就如何使输出保持我在字典中输入元素的顺序提出一些建议

请原谅我的无知,因为我正在努力自学,我刚刚开始学习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)

Tags: inonweight重量venusweightmarsweightsaturnweightneptuneweight
3条回答

这取决于你所说的“顺序”是什么意思:

for key, value in celestialWeight.items():
   print(key, value)

将按照您编写它们的顺序输出它们:

Weight on Sun:  4861.8
Weight on Mercury:  68.4
Weight on Venus:  163.8
Weight on Moon:  29.880000000000003
Weight on Mars:  68.4
Weight on Jupiter:  421.2
Weight on Saturn:  190.8
Weight on Uranus:  165.6
Weight on Neptune:  214.2
Weight on Pluto:  10.799999999999999

for key, value in sorted(list(celestialWeight.items())):
   print(key, value)

将按字母顺序输出它们:

Weight on Jupiter:  421.2
Weight on Mars:  68.4
Weight on Mercury:  68.4
Weight on Moon:  29.880000000000003
Weight on Neptune:  214.2
Weight on Pluto:  10.799999999999999
Weight on Saturn:  190.8
Weight on Sun:  4861.8
Weight on Uranus:  165.6
Weight on Venus:  163.8

如果要更改后验顺序,则可以这样做:

keys = list(celestialWeight.keys())
desired_order = [9,8,7,6,5,4,3,2,1,0]
reordered_dict = {keys[k]: celestialWeight[keys[k]] for k in desired_order_list}

它给出了一个倒排的列表:

{'Weight on Pluto: ': 10.799999999999999,
 'Weight on Neptune: ': 214.2,
 'Weight on Uranus: ': 165.6,
 'Weight on Saturn: ': 190.8,
 'Weight on Jupiter: ': 421.2,
 'Weight on Venus: ': 163.8,
 'Weight on Mars: ': 68.4,
 'Weight on Moon: ': 29.880000000000003,
 'Weight on Mercury: ': 68.4,
 'Weight on Sun: ': 4861.8}

与其他数据集合(列表、元组)相比,字典不使用索引,但是它们在字典中添加元素时保持元素的顺序

您当前获得与预期不同结果的原因是您正在应用以下内容:

sorted(list(celestialWeight.items())

函数的作用是:返回一个由(key,pair)组成的元组,然后将它转换成一个列表,然后根据ASCII值对它进行排序(因为我们所说的键是字符串)

您需要做的只是:

for key, value in celestialWeight.items():
    print(key, value)

您正在对词典进行排序,然后再打印。如果希望以插入顺序输出,请将sorted(list(celestialWeight.items()))更改为list(celestialWeight.items())。此外,我认为没有必要将这些项目转换为列表,因为它们已经是可编辑的了——这只会引入不必要的开销。你甚至可以只做celestialWeight.items()

相关问题 更多 >