8

我正在使用 Python 对列表进行无限迭代,多次重复列表中的每个元素。例如给定列表:

l = [1, 2, 3, 4]

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

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

我知道从哪里开始:

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

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

编辑

为了澄清这一点,应该无限迭代。此外,我使用重复元素两次作为最短示例 - 我真的很想将每个元素重复 n 次

更新

您的解决方案是否会引导我找到我正在寻找的东西:

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

感谢您的快速回答!

4

7 回答 7

13

这个怎么样:

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

编辑:合并bishanty 的重复计数参数和Adam Rosenfield 的列表理解

于 2008-12-20T18:36:27.197 回答
6

你可以很容易地用生成器来做到这一点:

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]
于 2008-12-20T18:31:49.577 回答
2
itertools.chain.from_iterable(itertools.repeat(item, repeat) for item in itertools.cycle(l))
于 2016-04-09T10:30:56.897 回答
1

解决方案应该类似于

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

编辑:添加“While (True)”以无限期迭代。

于 2008-12-20T18:30:05.603 回答
1
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))))
于 2008-12-22T16:32:41.080 回答
1

我这样做:

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
于 2017-10-24T23:38:20.713 回答
0
[ "%d, %d" % (i, i) for i in [1, 2, 3, 4] * 4]

最后4个是周期数。

于 2008-12-20T18:40:13.150 回答