Ad

How Could I Fill My Second List With Zero And One According To The Conditions Below?

- 1 answer

I have a list containing multiple lists. It's full of random numbers between 0 and 1.
I need to create another list with the same size of the first one, but if the random numbers less or equal to 0.75, I need them equal to zero and the more than 0.75 will be one. When I need to print the second list x, it must contain zeros and ones according to my conditions below. I always get a list full of zeros, where is my fault?

This is below my try:

import random

y = [[random.uniform(0,1) for i in range(10)]for j in range(10)]
x = [[0 for i in range(len(y[0]))]for j in range(len(y))]

for i in range(len(y)):
    for j in range(len(y[0])):
        if y[i][j] <= 0.75:
            x[i][j] == 0
        else:
            x[i][j] == 1
print(x)
Ad

Answer

Your if/else code is wrong, you are using '==' instead '=' so x[i] value is not being updated. Try this:

import random

y = [[random.uniform(0,1) for i in range(10)]for j in range(10)]
x = [[0 for i in range(len(y[0]))]for j in range(len(y))]

for i in range(len(y)):
    for j in range(len(y[0])):
        if y[i][j] <= 0.75:
            x[i][j] = 0
        else:
            x[i][j] = 1
print(x)
Ad
source: stackoverflow.com
Ad