如何迭代重复Python中每个元素的列表

时间:2021-10-08 13:42:27

I'm using Python to infinitely iterate over a list, repeating each element in the list a number of times. For example given the list:

我正在使用Python无限遍历列表,多次重复列表中的每个元素。例如给出列表:

l = [1, 2, 3, 4]

I would like to output each element two times and then repeat the cycle:

我想输出每个元素两次,然后重复循环:

1, 1, 2, 2, 3, 3, 4, 4, 1, 1, 2, 2 ... 

I've got an idea of where to start:

我知道从哪里开始:

def cycle(iterable):
  if not hasattr(cycle, 'state'):
    cycle.state = itertools.cycle(iterable)
  return cycle.next()

 >>> l = [1, 2, 3, 4]
 >>> cycle(l)
 1
 >>> cycle(l)
 2
 >>> cycle(l)
 3
 >>> cycle(l)
 4
 >>> cycle(l)
 1

But how would I repeat each element?

但是,我将如何重复每个元素?

Edit

To clarify this should iterate infinitely. Also I've used repeating the element twice as the shortest example - I would really like to repeat each element n times.

澄清这应该无限迭代。另外我用两次重复元素作为最短的例子 - 我真的想重复每个元素n次。

Update

Will your solution lead me to what I was looking for:

您的解决方案是否会引导我找到我想要的东西:

>>> import itertools
>>> def ncycle(iterable, n):
...   for item in itertools.cycle(iterable):
...     for i in range(n):
...       yield item
>>> a = ncycle([1,2], 2)
>>> a.next()
1
>>> a.next()
1
>>> a.next()
2
>>> a.next()
2
>>> a.next()
1
>>> a.next()
1
>>> a.next()
2
>>> a.next()
2

Thanks for the quick answers!

谢谢你的快速解答!

7 个解决方案

#1


How about this:

这个怎么样:

import itertools

def bicycle(iterable, repeat=1):
    for item in itertools.cycle(iterable):
        for _ in xrange(repeat):
            yield item

c = bicycle([1,2,3,4], 2)
print [c.next() for _ in xrange(10)]

EDIT: incorporated bishanty's repeat count parameter and Adam Rosenfield's list comprehension.

编辑:纳入bishanty的重复计数参数和亚当罗森菲尔德的列表理解。

#2


You could do it with a generator pretty easily:

您可以很容易地使用生成器来完成它:

def cycle(iterable):
    while True:
        for item in iterable:
            yield item
            yield item

x=[1,2,3]
c=cycle(x)

print [c.next() for i in range(10)]  // prints out [1,1,2,2,3,3,1,1,2,2]

#3


Solution should be something like

解决方案应该是这样的

iterable = [1, 2, 3, 4]
n = 2

while (True):
  for elem in iterable:
    for dummy in range(n):
      print elem # or call function, or whatever

Edit: added 'While (True)' to iterate indefinitely.

编辑:添加'While(True)'无限循环迭代。

#4


import itertools as it

def ncycle(iterable, n=1):
    if n == 1:
        return it.cycle(iterable)
    return it.cycle(it.chain(*it.izip(*([iterable]*n))))

#5


itertools.chain.from_iterable(itertools.repeat(item, repeat) for item in itertools.cycle(l))

#6


[ "%d, %d" % (i, i) for i in [1, 2, 3, 4] * 4]

The last 4 there is the number of cycles.

最后4个循环次数。

#7


I do it this way:

我是这样做的:

from itertools import cycle, repeat, chain
flatten = chain.from_iterable # better name

def ncycle(xs, n):
    return flatten(repeat(x, n) for x in cycle(xs))

# example
for n,x in enumerate(ncycle('abcd', 2)):
    print(x, end=" ")
    if n > 9:
        print("")
        break
# output: a a b b c c d d a a b

#1


How about this:

这个怎么样:

import itertools

def bicycle(iterable, repeat=1):
    for item in itertools.cycle(iterable):
        for _ in xrange(repeat):
            yield item

c = bicycle([1,2,3,4], 2)
print [c.next() for _ in xrange(10)]

EDIT: incorporated bishanty's repeat count parameter and Adam Rosenfield's list comprehension.

编辑:纳入bishanty的重复计数参数和亚当罗森菲尔德的列表理解。

#2


You could do it with a generator pretty easily:

您可以很容易地使用生成器来完成它:

def cycle(iterable):
    while True:
        for item in iterable:
            yield item
            yield item

x=[1,2,3]
c=cycle(x)

print [c.next() for i in range(10)]  // prints out [1,1,2,2,3,3,1,1,2,2]

#3


Solution should be something like

解决方案应该是这样的

iterable = [1, 2, 3, 4]
n = 2

while (True):
  for elem in iterable:
    for dummy in range(n):
      print elem # or call function, or whatever

Edit: added 'While (True)' to iterate indefinitely.

编辑:添加'While(True)'无限循环迭代。

#4


import itertools as it

def ncycle(iterable, n=1):
    if n == 1:
        return it.cycle(iterable)
    return it.cycle(it.chain(*it.izip(*([iterable]*n))))

#5


itertools.chain.from_iterable(itertools.repeat(item, repeat) for item in itertools.cycle(l))

#6


[ "%d, %d" % (i, i) for i in [1, 2, 3, 4] * 4]

The last 4 there is the number of cycles.

最后4个循环次数。

#7


I do it this way:

我是这样做的:

from itertools import cycle, repeat, chain
flatten = chain.from_iterable # better name

def ncycle(xs, n):
    return flatten(repeat(x, n) for x in cycle(xs))

# example
for n,x in enumerate(ncycle('abcd', 2)):
    print(x, end=" ")
    if n > 9:
        print("")
        break
# output: a a b b c c d d a a b