从增量开始位置创建循环迭代器

时间:2018-02-20 02:12:38

标签: python python-2.7 loops offset

好的,所以我想在索引中创建一个循环迭代器,就像这样

[0,1,2,3,4,5,6,7,8][1,2,3,4,5,6,7,8,0][2,3,4,5,6,7,8,0,1][3,4,5,6,7,8,0,1,2]...[8,0,1,2,3,4,5,6,7]

其中最大值可以是8或其他数字。

到目前为止,我有一些代码不起作用。

a = ['l','m','n','o','p','q','r','s','t'] #len(a) = 9
b = [[]] *len(a)
c = [[]] *len(a)
for offset_index in range(len(a)):
    b[offset_index] = []
    c[offset_index] = []
    for i in range(offset_index, len(a) - offset_index, 1):
        b[offset_index].append(i)
        c[offset_index].append(a[i])
print b
  

[[0,1,2,3,4,5,6,7,8],[1,2,3,4,5,6,7],[2,3,4,5,6] ],[3,4,5],[4],[],[],[],[]]

我可以看到它是第二个范围功能的问题,但无法想象一个整洁的修复。

5 个答案:

答案 0 :(得分:3)

itertools.cycle + itertools.islice

高效的循环和迭代 - 在编写此解决方案的过程中没有任何副本受到损害。

from itertools import cycle, islice

l = list(range(9))
repeats = 8

[list(islice(cycle(l), i, len(l) + i)) for i in range(repeats)]

[[0, 1, 2, 3, 4, 5, 6, 7, 8],
 [1, 2, 3, 4, 5, 6, 7, 8, 0],
 [2, 3, 4, 5, 6, 7, 8, 0, 1],
 [3, 4, 5, 6, 7, 8, 0, 1, 2],
 [4, 5, 6, 7, 8, 0, 1, 2, 3],
 [5, 6, 7, 8, 0, 1, 2, 3, 4],
 [6, 7, 8, 0, 1, 2, 3, 4, 5],
 [7, 8, 0, 1, 2, 3, 4, 5, 6]]

或者,如果您不想保留索引:

for i in range(repeats):
    idx = list(islice(cycle(l), i, len(l) + i)) 
    ... # do something with idx

列表理解

寻找表现的用户的选择。

[l[i:] + l[:i] for i in range(repeats)]

[[0, 1, 2, 3, 4, 5, 6, 7, 8],
 [1, 2, 3, 4, 5, 6, 7, 8, 0],
 [2, 3, 4, 5, 6, 7, 8, 0, 1],
 [3, 4, 5, 6, 7, 8, 0, 1, 2],
 [4, 5, 6, 7, 8, 0, 1, 2, 3],
 [5, 6, 7, 8, 0, 1, 2, 3, 4],
 [6, 7, 8, 0, 1, 2, 3, 4, 5],
 [7, 8, 0, 1, 2, 3, 4, 5, 6]]

答案 1 :(得分:2)

这是我的代码:

a = [1, 2, 3, 4, 5]
for slice_index in range(0, len(a)):
    print (a[slice_index::] + a[:slice_index:])
  

[1,2,3,4,5]
  [2,3,4,5,1]
  [3,4,5,1,2]
  [4,5,1,2,3]
  [5,1,2,3,4]

说明: a[slice_index::]给出数组中index> = slice_index的部分。另一个相同。

答案 2 :(得分:1)

a = [0,1,2,3,4,5,6,7,8]
b = []
for i in range(len(a)):
    b.append([])
    for j in range(len(a)):
        b[i].append(a[(i+j)%len(a)])

print b

答案 3 :(得分:1)

more_itertools.circular_shifts实施circular shiftscyclic permutation

<强>代码

import more_itertools as mit


iterable = range(9)

# Option 1
mit.circular_shifts(iterable)

输出

[(0, 1, 2, 3, 4, 5, 6, 7, 8),
 (1, 2, 3, 4, 5, 6, 7, 8, 0),
 (2, 3, 4, 5, 6, 7, 8, 0, 1),
 (3, 4, 5, 6, 7, 8, 0, 1, 2),
 (4, 5, 6, 7, 8, 0, 1, 2, 3),
 (5, 6, 7, 8, 0, 1, 2, 3, 4),
 (6, 7, 8, 0, 1, 2, 3, 4, 5),
 (7, 8, 0, 1, 2, 3, 4, 5, 6),
 (8, 0, 1, 2, 3, 4, 5, 6, 7)]

<强>替代

通过相同的sliding windows使用third-party library

import itertools as it


# Option 2
list(it.islice(mit.windowed(it.cycle(iterable), n=len(iterable)), len(iterable)))

# Option 3
list(mit.windowed(mit.ncycles(iterable, n=2), n=len(iterable)))[:-1]

答案 4 :(得分:0)

>>> L = ['a', 'b', 'c', 'd', 'e']
>>> [[L[i-j] for i in range(len(L))] for j in range(len(L), 0, -1)]
[['a', 'b', 'c', 'd', 'e'],
 ['b', 'c', 'd', 'e', 'a'],
 ['c', 'd', 'e', 'a', 'b'],
 ['d', 'e', 'a', 'b', 'c'],
 ['e', 'a', 'b', 'c', 'd']]