Reputation: 79
How would you shift left a list by x in Python, and fill the empty values with zeros?
shift left by 1
input: [1, 2, 3, 4]
output: [2, 3, 4, 0]
shift left by 2
input [1, 2, 3, 4]
output [3, 4, 0, 0]
Upvotes: 4
Views: 2059
Reputation: 7995
You can combine numpy's append
and roll
methods:
import numpy as np
def shift_left(x_, r):
return np.append(np.roll(x_, -r)[:-r], [0 for _ in range(0, r)])
print(shift_left([1, 2, 3, 4], 1))
print(shift_left([1, 2, 3, 4], 2))
Result:
[2 3 4 0]
[3 4 0 0]
Explanation
When you use roll
on a list:
print(np.roll([1, 2, 3, 4], -2))
Result:
[3 4 1 2]
You move the each element to the left by r
times (r
= -2). But we don't want the last r
elements so:
print(np.roll([1, 2, 3, 4], -2)[:-2])
Result:
[3 4]
We want the last r
values to be 0. So we can append r
0 to the end of the array.
print(np.append(np.roll([1, 2, 3, 4], -2)[:-2], [0 for _ in range(0, 2)]))
Result:
[3 4 0 0]
Upvotes: 1
Reputation: 2139
As far as I'm concerned, there's no 'easy' way, since Python's lists are not constrained by a size, but you can easily implement an algorithm which handles this:
def shift_left(arr, n):
return arr[n:] + [0 for _ in range(n)]
or a bit more consise:
def shift_left(arr, n):
return arr[n:] + [0] * n
Upvotes: 3
Reputation: 6035
You can concat two lists as:
arr[shift:]+[0]*shift
Or if you are a fan of chaining like me:
arr[shift:].__add__([0]*shift)
Upvotes: 1