在Python for循环中跳过可变数量的迭代

tlo*_*rin 2 python for-loop continue

我有一个列表和一个for循环,如下所示:

mylist = ['foo','foo','foo','bar,'bar','hello']
for item in mylist:
    cp = mylist.count(item)
    print("You "+item+" are present in "+str(cp)+" copy(ies)")
Run Code Online (Sandbox Code Playgroud)

输出:

You foo are present in 3 copy(ies)
You foo are present in 3 copy(ies)
You foo are present in 3 copy(ies)
You bar are present in 2 copy(ies)
You bar are present in 2 copy(ies)
You dude are present in 1 copy(ies)
Run Code Online (Sandbox Code Playgroud)

预期产量:

You foo are present in 3 copy(ies)
You bar are present in 2 copy(ies)
You dude are present in 1 copy(ies)
Run Code Online (Sandbox Code Playgroud)

因此,想法是在for循环中跳过可变数量的迭代,使用类似这样的脚本(不工作):

for item in mylist:
    cp = mylist.count(item)
    print("You "+item+" are present in "+str(cp)+" copy(ies)")
    continue(cp)
Run Code Online (Sandbox Code Playgroud)

因此,脚本将cp在每一轮"跳转" for循环中的元素,并再次开始在项目中询问它item + cp.

我知道您可以使用continue跳过多次迭代(例如在这篇文章中),但我无法弄清楚如何使用continue跳过可变数量的迭代.

感谢您的回答!:)


编辑:类似的项目总是彼此相邻.

Tom*_*ton 5

你可以使用Counter:

from collections import Counter

mylist = ['foo','foo','foo','bar','bar','hello']
c = Counter(mylist)
for item, cp in c.items():
    print("You "+item+" are present in "+str(cp)+" copy(ies)")
Run Code Online (Sandbox Code Playgroud)