创建编号列表的输出 [英] Creating numbered list of output

查看:57
本文介绍了创建编号列表的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何编辑代码以使输出:

How can I edit my code such that my output:

the      8512
and      7759
i        6182
to       6027
a        4716
of       4619
he       2873
in       2846
you      2777
was      2457

成为

1.    the    8512
2.    and    7759
3.    i      6182
4.    to     6027
5.    a      4716
6.    of     4619
7.    he     2873
8.    in     2846
9.    you    2777
10.   was    2457

我尝试使用枚举功能

for rank, (value,num) in enumerate(sorted_list):

但是,这给了我相同的输出.我能以某种方式将排名附加到定义了value和num的列表中吗?

however this leaves me with the same output. Could I somehow append ranking into the list where value and num is defined?

d = dictionary(word_list)


def sort_key (d):
    return d[1]

number = int(sys.argv[1])
sorted_list = sorted(d.items(), key=sort_key, reverse=True)[:number]


for (value,num) in sorted_list:
    value = value.ljust(5)
    num = str(num).rjust(5)

    print("{}\t{}".format(value,num))

推荐答案

您仍将使用enumerate();您没有显示如何使用它,但是它可以解决您的问题:

You'd still use enumerate(); you didn't show how you used it but it but it solves your issue:

for index, (value,num) in enumerate(sorted_list, start=1):
    print("{}.\t{:<5}\t{:>5}".format(index, value,num))

我将您的str.ljust()str.rjust()调用折叠到了str.format()模板中;这样做的另一个好处是,它将适用于您可以设置格式的任何值,而不仅仅是字符串.

I folded your str.ljust() and str.rjust() calls into the str.format() template; this has the added advantage that it'll work for any value you can format, not just strings.

演示:

>>> word_list = '''\
... the      8512
... and      7759
... i        6182
... to       6027
... a        4716
... of       4619
... he       2873
... in       2846
... you      2777
... was      2457
... '''.splitlines()
>>> d = dict(line.split() for line in word_list)
>>> sorted_list = sorted(d.items(), key=lambda i: i[1], reverse=True)
>>> for index, (value,num) in enumerate(sorted_list, start=1):
...     print("{}.\t{:<5}\t{:>5}".format(index, value,num))
... 
1.  the      8512
2.  and      7759
3.  i        6182
4.  to       6027
5.  a        4716
6.  of       4619
7.  he       2873
8.  in       2846
9.  you      2777
10. was      2457

这篇关于创建编号列表的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆