I would like to group list elements in groups of three and make the second element of the list to start the second group of elements for example;
arr = [1,2,3,4,5,6,7,8,9]
#expected output
output = [[1,2,3],[2,3,4],[3,4,5],[4,5,6],[5,6,7],[6,7,8],[7,8,9]]
How do I do this with python?
CodePudding user response:
You can just use a list comprehension -
[arr[i:i 3] for i in range(len(arr)-2)]
CodePudding user response:
Hello dear friend try to create new lists then append them to another list:
arr = [1,2,3,4,5,6,7,8,9]
i = 0
b = []
while i <= len(arr) - 3:
a = [arr[i],arr[i 1],arr[i 2]]
b.append(a)
i = 1
print(b)
OUTPUT
[[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9]]