问题
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
becomes
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
I attempted to use the enumerate function
for rank, (value,num) in enumerate(sorted_list):
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))
回答1:
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))
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.
Demo:
>>> 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
来源:https://stackoverflow.com/questions/29074749/creating-numbered-list-of-output