如何用计数器在python中循环?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (832)

如何使用计数器创建for循环?我有一个列表,我想在每个元素之后阅读一个元素n元素。我一开始就这么做的

for i in enumerate(n):
    print(i)

但是,正如预期的那样,它打印每个元素而不是每个第n个元素,Python解决这个问题的方法是什么?

提问于
用户回答回答于

我不确定是否有价值n但通常有这样的方法:

for index, item in enumerate(n):
   if index % nth == 0: # If the output is not like you want, try doing (index + 1), or enumerate(n, start=1).
       print(item)

其他方式可以是:

for index in range(0, len(n), nth): # Only work with sequences
   print(n[index]) # If the output is not like you want, try doing n[index + 1]

或:

for item in n[::nth]: # Low perfomance and hight memory consumption warning!! Only work with sequences
    print(item)

甚至可以将第一个和最后一个组合起来:

for i, item in list(enumerate(n))[::nth]: # Huge low perfomance warning!!!
    print(item)

但我不确定这是否有优势.。

此外,如果愿意创建一个函数,则可以执行类似于enumerate

def myEnumerate(sequence, start=0, jump=1):
    n = start
    j = start // Or j = 0, that is your decision.
    for elem in sequence:
        if j % jump == 0:
            yield n, elem
            n += 1
        j += 1

for index, item in myEnumerate(n, jump=1):
    print(item)
n = 'a b c d e f g h i j k l m n ñ o p q r s t u v w x y z 1 2 3 4 5 6 7 8 9 ! " · $ % & / ( ) = ? ¿ Ç ç } { [ ] ; : _ ¨ ^ * ` + ´ - . , º ª \ /'.split(" ")
nth = 3    
def a():
    for i, item in enumerate(n):
       if i % nth == 0:
           item       
def b():
    for item in range(0, len(n), nth):
       n[item]           
def c():
    for item in n[::nth]:
        item    
def d():
    for i, item in list(enumerate(n))[::nth]:
       if i % nth == 0:
           item    
def enumerates(sequence, start=0, jump=1):
    n = start
    j = start
    for elem in sequence:
        if j % jump == 0:
            yield n, elem
            n += 1
        j += 1            
def e():
    for i, item in enumerates(n, jump= nth):
        item    
if __name__ == '__main__':
    import timeit
    print(timeit.timeit("a()", setup="from __main__ import a")) # 10.556324407152305
    print(timeit.timeit("b()", setup="from __main__ import b")) # 2.7166204783010137
    print(timeit.timeit("c()", setup="from __main__ import c")) # 1.0285353306076601
    print(timeit.timeit("d()", setup="from __main__ import d")) # 8.283859051918608
    print(timeit.timeit("e()", setup="from __main__ import e")) # 14.91601851631981
用户回答回答于

使用itertools.islice()对象将迭代限制在n-这个物体,这是至少其速度是任何其他拟议解决方案的两倍:

from itertools import islice

n = 5
for ob in islice(iterable, None, None, n):
    print(ob)

上面提到的每五个物体就会产生一次:

>>> from itertools import islice
>>> from string import ascii_uppercase as iterable
>>> n = 5
>>> for ob in islice(iterable, None, None, n):
...     print(ob)
...
A
F
K
P
U
Z

替换第一个None带着n - 1如果您想跳到n对象作为第一个使用的对象:

>>> for ob in islice(iterable, n - 1, None, n):
...     print(ob)
...
E
J
O
T
Y

没有创建输入序列的副本来实现这一点,因此不需要额外的内存或时间来生成结果。把每一个n-这个对象比一个%的一个指数的模数测试enumerate()有可能成功,或者用range()生成索引。这是因为不需要进一步的Python字节码步骤来进行额外的测试或索引操作。

如果你需要以这种方式选择项的索引,请添加enumerate()通过包装可迭代性返回:

>>> for i, ob in islice(enumerate(iterable), n - 1, None, n):
...     print(i, ob)
...
4 E
9 J
14 O
19 T
24 Y

islice()如果你需要速度的话,就比其他任何解决方案都快:

>>> from timeit import timeit
>>> from itertools import islice
>>> import random
>>> testdata = [random.randrange(1000) for _ in range(1000000)]  # 1 million random numbers
>>> def islice_loop(it):
...     for ob in islice(it, None, None, 5): pass
...
>>> def range_loop(it):
...     for i in range(0, len(it), 5): ob = it[i]
...
>>> def slice_loop(it):
...     for ob in it[::5]: pass
...
>>> def enumerate_test_loop(it):
...     for i, ob in enumerate(it):
...         if i % 5 == 0: pass
...
>>> def enumerate_list_slice_loop(it):
...     for i, ob in list(enumerate(it))[::5]: pass
...
>>> timeit('tf(t)', 'from __main__ import testdata as t, islice_loop as tf', number=1000)
4.194277995004086
>>> timeit('tf(t)', 'from __main__ import testdata as t, range_loop as tf', number=1000)
11.904250939987833
>>> timeit('tf(t)', 'from __main__ import testdata as t, slice_loop as tf', number=1000)
8.32347785399179
>>> timeit('tf(t)', 'from __main__ import testdata as t, enumerate_list_slice_loop as tf', number=1000)
198.1711291699903

扫码关注云+社区

领取腾讯云代金券