Warm tip: This article is reproduced from serverfault.com, please click

count-如何在Python中删除重复打印?

(count - How to remove duplicate prints in Python?)

发布于 2020-12-02 09:13:07

因此,我想编写一个程序,该程序可以打印出列表中重复数字的次数。我是Python的新手,我使用.count()命令来获取元素重复的次数。我希望输出遵循“数字n重复n次”的格式

这是我到目前为止所拥有的:

x = [1,1,2,4,5,7,2,3,3,8,2,3,6,7]
index = 0 
while index < len(x):
print('The number {} is repeated {} times.'.format(x[index],x.count(x[index])))
index = index + 1 

这是输出:

The number 1 is repeated 2 times
The number 1 is repeated 2 times
The number 2 is repeated 3 times
The number 4 is repeated 1 times
The number 5 is repeated 1 times
The number 7 is repeated 2 times
The number 2 is repeated 3 times
The number 3 is repeated 3 times
The number 3 is repeated 3 times
The number 8 is repeated 1 times
The number 2 is repeated 3 times
The number 3 is repeated 3 times
The number 6 is repeated 1 times
The number 7 is repeated 2 times

我希望输出显示一个数字以升序重复一次。我如何使输出像这样输出:

The number 1 is repeated 2 times.
The number 2 is repeated 3 times. 
The number 3 is repeated 3 times. 
...

谢谢!:)

Questioner
nimbusmom
Viewed
0
solid.py 2020-12-02 17:47:48

这将对所有出现的数字进行计数并以升序打印。

from collections import Counter

x = [1, 1, 2, 4, 5, 7, 2, 3, 3, 8, 2, 3, 6, 7]

for key, val in sorted(Counter(x).items()):
    print(f'The number {key} is repeated {val} times.')

代码输出:

The number 1 is repeated 2 times.
The number 2 is repeated 3 times.
The number 3 is repeated 3 times.
The number 4 is repeated 1 times.
The number 5 is repeated 1 times.
The number 6 is repeated 1 times.
The number 7 is repeated 2 times.
The number 8 is repeated 1 times.