【Python、练习题】排序妙用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lnotime/article/details/89018704

Python 3.7.1 

题目:生成包括N(=1000)个0-100之间的随机分数,统计其中各个分数出现的次数,按照出现次数的从高到低的顺序(不包括出现次数为0的分数)打印出来。首先采用每行:分数 次数格式输出其次每行: 次数:分数1、分数2.... 的格式输出最终是下面这种输出结果

import random

score_num = {}
for _ in range(1000):
    score = random.randint(1, 100)
    score_num[score] = score_num.get(score, 0) + 1

num_scores = {}

for score, num in sorted(score_num.items(), key=lambda sn: (-sn[1], sn[0])):
    print(f'{score}\t{num}')

    if num in num_scores:
        num_scores[num].append(str(score))
    else:
        num_scores[num] = [str(score)]

print()  # 空行

for num, scores in sorted(num_scores.items(), key=lambda ns:(-ns[0], ns[1])):
    print(f'次数 {num}\t: {", ".join(scores)}')

妙处在于storeted处,如果用reversed来控制排序方向的话,会超过79个字符,所以可以用正负号来控制方向,真的棒哈哈哈哈哈。以前我是从来没这么用过,这次是怎么想到的呢,这个题本身需要对二层排序结果做与一层排序方向相反的排序,所以才想到用正负号来处理,所以才想到把reverse去掉的。 

\t 是为了美化输出

猜你喜欢

转载自blog.csdn.net/lnotime/article/details/89018704