Home > Mobile >  Replace the first value of a 2d list to zero
Replace the first value of a 2d list to zero

Time:08-28

Having 2d list as below:

a = [[4.0, 4, 4.0], [3.0, 3, 3.6], [3.5, 6, 4.8]]

need to replace first value to zero.

a = [[0, 4, 4.0], [0, 3, 3.6], [0, 6, 4.8]]

I tried to iterate over the 2d list:

[i[0] for i in a]

CodePudding user response:

Because you tag , you can do this without iterate like below:

import numpy as np

a_2 = np.asarray(a)
a_2[:, 0] = 0
# --^^^^ -> : -> mean all rows and (0) mean is column==0
print(a_2)

[[0.  4.  4. ]
 [0.  3.  3.6]
 [0.  6.  4.8]]

CodePudding user response:

if you're going to do it using list comprehension, you have to think in terms of generating a new list, and not modifying the original list in place:

a = [[4.0, 4, 4.0], [3.0, 3, 3.6], [3.5, 6, 4.8]]
b = [[0, *x[1:]] for x in a]
print(b)

CodePudding user response:

You could try something like this:

example = [[4.0, 4, 4.0], [3.0, 3, 3.6], [3.5, 6, 4.8]]

# convert the first element of each list to 0
example = [[0, *x[1:]] for x in example]

print(example)
  • Related