【发布时间】:2016-10-15 00:10:57
【问题描述】:
我有一个列表和一个 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)")
输出:
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)
预期输出:
You foo are present in 3 copy(ies)
You bar are present in 2 copy(ies)
You dude are present in 1 copy(ies)
因此,我们的想法是在 for 循环中跳过可变数量的迭代,使用类似以下脚本(不工作):
for item in mylist:
cp = mylist.count(item)
print("You "+item+" are present in "+str(cp)+" copy(ies)")
continue(cp)
因此,该脚本将在每一轮中“跳转”for 循环中的cp 元素,并再次开始执行它在项目item + cp 处所要求的操作。
我知道您可以使用continue 来跳过多次迭代(例如在this post 中),但我不知道如何使用continue 来跳过可变数量的迭代。
感谢您的回答! :)
编辑:相似的项目总是彼此相邻。
【问题讨论】:
-
这个列表是否总是排序/分组,例如相同的元素总是在一起?
-
@Jerzyk 确实如此!