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

时间:2016-06-14 10:07:13

标签: python for-loop continue

我有一个列表和一个for循环,例如:

urllib

输出:

from Bio import Entrez

Entrez.email = "Your.Name.Here@example.org"


#id is a string list with pubmed IDs
#two of have a public PMC article, one does not
handle = Entrez.efetch("pubmed", id="19304878,19088134", retmode="xml")

records = Entrez.parse(handle)
#checks for all records if they have a PMC identifier
#prints the URL for downloading the PDF
for record in records:
    if record.get('MedlineCitation'):
        if record['MedlineCitation'].get('OtherID'):
           for other_id in record['MedlineCitation']['OtherID']:
               if other_id.title().startswith('Pmc'):
                   print('http://www.ncbi.nlm.nih.gov/pmc/articles/%s/pdf/' % (other_id.title().upper()))

预期输出:

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)")

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

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)

因此,脚本会在每一轮“跳转”for循环中的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 item in mylist: cp = mylist.count(item) print("You "+item+" are present in "+str(cp)+" copy(ies)") continue(cp) 项中的询问。

我知道您可以使用cp跳过多次迭代(例如在this post中),但我无法弄清楚如何使用item + cp跳过变量数迭代

感谢您的回答! :)

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

7 个答案:

答案 0 :(得分: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)")

答案 1 :(得分:3)

您可以将collections.Counter用于您的工作:

>>> from collections import Counter
>>> Counter(['foo', 'foo', 'bar'])
Counter({'foo': 2, 'bar': 1})

因此,

count_dict = Counter(mylist)
for item in count_dict:
    print("You "+item+" are present in "+str(count_dict[item[)+" copy(ies)")

答案 2 :(得分:2)

您可以使用set

获取列表的唯一元素
CONCAT()

输出:

  

你的酒吧出现在2份副本中

     

你好,你有1份副本

     

你好foo出现在3个副本中

答案 3 :(得分:2)

你也可以这样做

mylist = ['foo','foo','foo','bar','bar','hello']
prev = None
for item in mylist:
    if item != prev:
        cp = mylist.count(item)
        print("You "+item+" are present in "+str(cp)+" copy(ies)")
        prev = item
希望它可能有所帮助!

答案 4 :(得分:2)

由于元素是连续的,你可以使用groupby来对连续的字符串进行分组,只需要计算每个组的长度来计算:

from itertools import groupby
mylist = ['foo','foo','foo','bar','bar','hello']

for k,v in groupby(mylist):
    print("You {} are present in {} copy(ies)".format(k, sum(1 for _ in v)))

输出:

You foo are present in 3 copy(ies)
You bar are present in 2 copy(ies)
You hello are present in 1 copy(ies)

通常获得计数的最有效方法是使用字典逻辑,如其他答案中提供的 Counter ,如果你想保持顺序,你可以使用 OrderedDict 做计数:

from collections import OrderedDict
mylist = ['foo','foo','foo','bar','bar','hello']
od = OrderedDict()
for ele in mylist:
    od.setdefault(ele, 0)
    od[ele] += 1

for tup in od.items():
    print("You {} are present in {} copy(ies)".format(*tup))

哪个会输出相同的内容:

You foo are present in 3 copy(ies)
You bar are present in 2 copy(ies)
You hello are present in 1 copy(ies)

groupby dict 逻辑都是O(n),使用list.count是二次方。

答案 5 :(得分:1)

mylist = ['foo','foo','foo','bar','bar','hello']
last = None
for item in mylist:
    if item is last:
        continue

    last = item
    cp = mylist.count(item)
    print("You "+item+" are present in "+str(cp)+" copy(ies)")

这假定列表是有序的,以便相同的对象彼此相邻。

答案 6 :(得分:1)

setlist counts可以解决问题:

mylist = ['foo','foo','foo','bar','bar','hello']
for item in set(mylist):
    print("You "+item+" are present in "+str(mylist.count(item))+" copy(ies)")

输出:

You foo are present in 3 copy(ies)
You bar are present in 2 copy(ies)
You hello are present in 1 copy(ies)