给出一个列表,例如。 [2,3,4,10,20,30,102] 我需要所有可能的长度为3的块/子列表,如下所示,
[[2, 3, 4], [3, 4, 10], [4, 10, 20], [10, 20, 30], [20, 30, 102]]
答案 0 :(得分:2)
这将完成这项工作:
l= [2,3,4,10,20,30,102]
res=[l[i:i+3] for i in range(len(l)-2)]
print(res)
打印
[[2, 3, 4], [3, 4, 10], [4, 10, 20], [10, 20, 30], [20, 30, 102]]
答案 1 :(得分:1)
这个功能可以完成更多的工作
def chunks(sequence, length):
sub_sequences = [sequence[offset:]
for offset in range(length)]
return zip(*sub_sequences)
为你的例子
list(chunks([2, 3, 4, 10, 20, 30, 102], length=3))
提供所需的输出
答案 2 :(得分:1)
使用list comprehension和xrange操作会帮到您。
示例输出
>>> a = [2,3,4,10,20,30,102]
>>> max_len = 3
>>> [ a[i-max_len: i] for i in xrange(max_len, len(a))]
[[2, 3, 4], [3, 4, 10], [4, 10, 20], [10, 20, 30]]
>>> max_len = 5
>>> [ a[i-max_len: i] for i in xrange(max_len, len(a))]
[[2, 3, 4, 10, 20], [3, 4, 10, 20, 30]]
答案 3 :(得分:0)
arr = [2,3,4,10,20,30,102]
arr2 = arr
arr3 =[]
while (len(arr2) >= 3):
arr4=arr2[:3]
arr2 = arr2[1:]
arr3.append(arr4)
print("Original List \n")
print(arr)
print("\n")
print("List with all the chunks \n")
print(arr3)
答案 4 :(得分:0)
最简单的方法是使用切片:
>>> s = [2, 3, 4, 10, 20, 30, 102]
>>> [s[i:i+3] for i in range(0, len(s)-2)]
[[2, 3, 4], [3, 4, 10], [4, 10, 20], [10, 20, 30], [20, 30, 102]]