listA = ["A","B","C","D"]
由此,我只想要以下输出:
["A","B","C"]
["B","C","D"]
["C","D","A"]
["D","A","B"]
我已经在这里查看了关于排列的各种问题,但到目前为止我无法做到这一点。任何帮助将不胜感激。
答案 0 :(得分:3)
另一种方法 - 蛮力,
def permutation(L):
for i in range(len(L)):
x = L[i:i+3]
length = len(x)
if length != 3:
x = x + L[:3-length]
print(x)
L = ["A","B","C","D"]
permutation(L)
答案 1 :(得分:3)
您可以使用itertools.cycle
和itertools.islice
。
要获取您显示的订单(建议@tobias_k):
>>> from itertools import cycle, islice
>>> listA = ["A","B","C","D"]
>>> [list(islice(cycle(listA), i, i+3)) for i in range(len(listA))]
[['A', 'B', 'C'], ['B', 'C', 'D'], ['C', 'D', 'A'], ['D', 'A', 'B']]
要获得另一种顺序排序:
>>> it = cycle(listA)
>>> [list(islice(it,3)) for _ in range(len(listA))]
[['A', 'B', 'C'], ['D', 'A', 'B'], ['C', 'D', 'A'], ['B', 'C', 'D']]
答案 2 :(得分:0)
感谢您的所有答案。我收到了一位朋友的回答,我想在这里分享一下。它是这样的。
listA = ["A","B","C","D"]
listB = listA + [listA[0]] + [listA[1]]
catch = []
for i in range(len(listA)):
A = listB[i]
B = listB[i+1]
C = listB[i+2]
catch.append([A,B,C])
print catch