Reputation: 171
I have two lists.
a = [1,2,3,4,0,4,5,6,3,6,0,5,6,8,0,3]
b = [1,2, None,4,5,4,5,6,3,6,7,5,6,8,4, None]
I want a resulting list like this.
new_list = [1,2,3,4,5,4,5,6,3,6,7,5,6,8,4,3]
List b is only replacing the 0's in list a and not touching the other elements for example the None is not being replaced.
How can I get about doing this? Thanks in advance. Please do let me know if you need any other information.
I have tried the following and it does not work.
_ = dict(zip(a,b))
for k,v in _.items():
if k == 0:
a = a.replace(k,v)
Upvotes: 2
Views: 2098
Reputation: 1927
out = []
for ea, eb in zip(a, b):
res = ea
# if element in a is 0 and corresponding element in b is not None
if ea == 0 and eb:
res = eb
out.append(res)
assert out == [1,2,3,4,5,4,5,6,3,6,7,5,6,8,4,3]
And for a = [0, 1, 0]
and b = [None, 2, 3]
this will generate
out == [0, 1, 3]
Upvotes: 0
Reputation: 71580
Or enumerate
+ a loop + indexing:
l=[i for i,v in enumerate(a) if v==0]
for i in l:
a[i]=b[i]
And now:
print(a)
Is:
[1, 2, 3, 4, 5, 4, 5, 6, 3, 6, 7, 5, 6, 8, 4, 3]
Upvotes: 0
Reputation:
try with this:
a = [1, 0, 3, 4, 0, 6, 7, 0, 9]
b = [1, 2, None, 4, 5, 6, None, 8, 9]
k = 0 # Counter
c = [0] * len(a) # Creating the 'c' list
for n in a: # Reading 'a' list
if n != 0:
c[k] = a[k] # Copying 'a' list objects, when 'n' != 0, in 'c' list
else:
c[k] = b[k] # Copying 'b' list objects, when 'n' == 0, in 'c' list
k = k + 1
Upvotes: 0
Reputation: 12990
You can use zip
and a simple list comprehension to generate a new list by picking elements of a
if they're not 0 or elements of b
if the corresponding a
element is zero:
a = [1, 2, 3, 4, 0, 4, 5, 6, 3, 6, 0, 5, 6, 8, 0, 3]
b = [1, 2, None, 4, 5, 4, 5, 6, 3, 6, 7, 5, 6, 8, 4, None]
result = [y if x == 0 else x for x, y in zip(a, b)]
print(result)
# [1, 2, 3, 4, 5, 4, 5, 6, 3, 6, 7, 5, 6, 8, 4, 3]
Upvotes: 3