如果我有大名单A = [1,2,3,4,5,6,7,8,9,10] 我有3个元素的子列表,例如
B = [1,2,3]
我想根据A列表向前滑动1步,因此B变为[2,3,4] - 是否有顺利的方法可以做到这一点?或者我只需要弹出B的第一个元素然后从A?
添加适当的元素谢谢!
编辑:我的回答 B = A [i:i + 3] 如果你想通过'i'步骤向前看,你可以增加'i'。答案 0 :(得分:3)
您可以A
成为deque
:
from collections import deque
A = deque(range(1,11))
B
可以是A
的前3个元素的视图。当您需要“滑动”时,请向左旋转A
。
A
Out[71]: deque([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
from itertools import islice #deques do not support slicing notation
B = list(islice(A,3))
B
Out[74]: [1, 2, 3]
A.rotate(-1)
B = list(islice(A,3))
B
Out[77]: [2, 3, 4]
答案 1 :(得分:1)
for i in range(len(a)-2):
b = a[i:i+3]
print b
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
[4, 5, 6]
[5, 6, 7]
[6, 7, 8]
[7, 8, 9]
[8, 9, 10]
你可以更普遍地做。
答案 2 :(得分:0)
>>> A = [1,2,3,4,5,6,7,8,9,10]
>>> for B in (A[i - 3: i] for i in range(3, len(A) + 1)):
... print B
...
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
[4, 5, 6]
[5, 6, 7]
[6, 7, 8]
[7, 8, 9]
[8, 9, 10]
答案 3 :(得分:0)
使用itertools
:
>>> from itertools import islice, izip
>>> A = [1,2,3,4,5,6,7,8,9,10]
>>> for l in izip(*(islice(A, x, None) for x in xrange(3))):
... print list(l)
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
[4, 5, 6]
[5, 6, 7]
[6, 7, 8]
[7, 8, 9]
[8, 9, 10]
islice(A, x, None)
在A[x:]
上创建一个迭代器。