GWasp
GWasp

Reputation: 51

Multiple if and if not in list comprehension

I tried to look at similar questions but I'm really not understanding how I can accomplish this using the methods mentioned in the other questions. So my problem is: I have one list from which I want to remove certain values. For instance:

a = [[[0,0],[0,1]],[[0,0],[0,1]]]
for y in range(2):
    a[y][:] = [x for x in a[y] if not random.random() < s]

This removes the elements for which random.random() is below s (being s between 0 and 1). However, I only want this to happen if the second position of each element of the list (that is the [0,0] bit) is equal to 1. I tried multiple solutions (suggested around here for other questions) and I can't get it to work. Does anyone have any suggestion?

Upvotes: 1

Views: 44

Answers (1)

Elisha
Elisha

Reputation: 23770

Another condition could be added to check the value of the second "bit" of x (x[1] == 0):

a = [[[0,0],[0,1]],[[0,0],[0,1]]]
for y in range(2):
    a[y][:] = [x for x in a[y] if x[1] == 0 or random.random() >= 0.5]

This means that if x[1] == 0, then the pair is kept, regardless of a random value. Otherwise, it is kept only if random.random() >= 0.5.

Upvotes: 1

Related Questions