Home > Blockchain >  Change values in one column based on values in another
Change values in one column based on values in another

Time:05-06

list_x = [1,0,0,3,0,5,6,7]

list_y = [10,20,30,40,50,60,70,80]

list_z = [100,200,300,400,500,600,700,800]



desired_y = [0,20,30,0,50,0,0,0]
desired_z = [0,200,300,0,500,0,0,0]

My goal is for every 0 value in list x I want the corresponding output in list y and z, and if there is a value, then I want it to display the list. Any Ideas?

CodePudding user response:

With list comprehension:

list_y = [i if j else j for i, j in zip(list_y, list_x)]
list_z = [i if j else j for i, j in zip(list_z, list_x)]

print(list_y, list_z)

Output:

[10, 0, 0, 40, 0, 60, 70, 80] [100, 0, 0, 400, 0, 600, 700, 800]

Edit: Answering 2nd question in comments:

list_y = [0 if j>0 else i for i, j in zip(list_y, list_x)]
list_z = [0 if j>0 else i for i, j in zip(list_z, list_x)]
print(list_y, list_z)

Output:

[0, 20, 30, 0, 50, 0, 0, 0] [0, 200, 300, 0, 500, 0, 0, 0]

CodePudding user response:

Try:

list_x = [1, 0, 0, 3, 0, 5, 6, 7]
list_y = [10, 20, 30, 40, 50, 60, 70, 80]
list_z = [100, 200, 300, 400, 500, 600, 700, 800]

desired_y, desired_z = [], []
for x, y, z in zip(list_x, list_y, list_z):
    desired_y.append(0 if x else y)
    desired_z.append(0 if x else z)

print(desired_y)
print(desired_z)

Prints:

[0, 20, 30, 0, 50, 0, 0, 0]
[0, 200, 300, 0, 500, 0, 0, 0]
  • Related