I have a thousand numbers in a list like this:
A=[1,2,3,4]
I want to covert this in the following format:
desired_A=[[1,2],[2,3],[3,4]]
How can I do this?
I have a thousand numbers in a list like this:
A=[1,2,3,4]
I want to covert this in the following format:
desired_A=[[1,2],[2,3],[3,4]]
How can I do this?
You can use zip()
and a list comprehension like:
desired = [[a, b] for a, b in zip(A, A[1:])]
A = [1, 2, 3, 4]
desired = [[a, b] for a, b in zip(A, A[1:])]
print(desired)
[[1, 2], [2, 3], [3, 4]]
You can do it in one neat list comprehension. You are creating a new list where for each element in A, the new list has a list that contains that element and the element after that element.
desired_A = [[A[i], A[i+1]] for i in range(len(A)-1)]