Reputation: 633
What i would like to do is to initialize an array which has 5 elements set to 0 and then copy the other array to the first one, something like this:
a = [0, 0, 0, 0, 0]
b = [1, 2, 3]
print a | b
[1, 2, 3, 0, 0]
Is there any pythonic way in doing so except:
for i, x in enumerate(b):
a[i] = x
Edit:
I forgot to mention that buffer a
will always be filled with plain zeroes at the beginning and condition len(b) < len(a)
is always true
, also in each case buffer a
will always start getting overwritten from index 0
.
Ill explain why i need this kind of behaviour in the first place, basicly I have a raw 256-byte UDP frame. Buffer a
corresponds to bytes 16-31 in the frame. Depending on some conditions, those bytes will either be overwritten or be set at 0, length of b
is always 12.
def foo(b=12*[0]):
a = 16*[0]
return a[:12] = b[:]
Upvotes: 0
Views: 554
Reputation: 411
Something like this (Note: XOR operator is ^
?
import itertools
a = [0, 0, 0, 0, 0]
b = [1, 2, 3]
def safeXOR(arr1, arr2):
return list((x ^ y for (x, y) in itertools.zip_longest(arr1, arr2, fillvalue=0)))
print(safeXOR(a,b))
Upvotes: 0
Reputation: 59425
Why waste time defining a
in the first place? You can simply append the correct number of 0
s to b
instead:
>>> b = [1, 2, 3]
>>> a = b + [0] * (5 - len(b))
>>> a
[1, 2, 3, 0, 0]
Upvotes: 1
Reputation: 842
This works in Python 2:
import itertools
a = [0, 0, 0, 0, 0]
b = [1, 2, 3]
g = (l | r for (l, r) in itertools.izip_longest(a, b, fillvalue=0))
print list(g)
And this in Python 3:
import itertools
a = [0, 0, 0, 0, 0]
b = [1, 2, 3]
g = (l | r for (l, r) in itertools.zip_longest(a, b, fillvalue=0))
print(list(g))
I created a generator g
but if you know in advance you want all values of it already, then it's okay to have a list comprehension right away instead.
This is the doc for zip_longest
: https://docs.python.org/3/library/itertools.html#itertools.zip_longest
Directly with the list comprehension (py3):
import itertools
a = [0, 0, 0, 0, 0]
b = [1, 2, 3]
g = [l | r for (l, r) in itertools.zip_longest(a, b, fillvalue=0)]
print(g)
Upvotes: 1