繁体   English   中英

如果键是 python 中的数字,有没有办法按键对字典进行排序?

[英]Is there a way to sort a dictionary by keys if the keys are numbers in python?

我试图编写一个代码来帮助我完成统计作业。 该代码确实有效,但 output 非常不可读,因为它没有按数字排序。 有没有办法在这里对数字进行排序? 这是我的代码:

from time import sleep
numbers = {}
newList = []
total = 0
tempint = 0
keynum = 0
print("In this program you can input all the numbers given in a list, and you will get a result of how many numbers there are of any unique numbers, frequency, relavitve frequency and how many in total.")
sleep(2)
while True:
    inp = input("Enter a number in the list (press enter to stop the program)")
    if inp == '': break 
    if not f'{inp}' in numbers:
       numbers[f'{inp}'] = [1]
    else: numbers[f'{inp}'].append(1)
for key,value in numbers.items():   
    total += len(value)
for key,value in sorted(numbers.items()):
    freq = len(value)
    print(f'{key} - frequency: {freq}, relative frequency: {freq/total*100}%')
print(f'Total amount: {total}')
for key,value in numbers.items():
    tempint += int(key)                 
    keynum += 1
print(f'Unique numbers: {keynum}')
print(f'Average: {tempint/keynum}')

当我运行程序时,我希望 output 看起来像这样:

1 - frequency: 2, relative frequency: 28.57142857142857% 2 - frequency: 1, relative frequency: 14.285714285714285% 3 - frequency: 3, relative frequency: 42.857142857142854% 4 - frequency: 1, relative frequency: 14.285714285714285% Total amount: 7 Unique numbers: 4 Average: 2.5所以基本上是按行首的数字排序的,这些数字代表字典中的键。 我将不胜感激任何帮助。

您可以使用OrderedDict按键对dict进行排序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM