3

I have two arrays, one array that contains all indices of two arrays that meet a certain condition I had made previous to this. The other array is an array of booleans. I want to take the array of indices and find the same place in the array of booleans and replace those values.

So for example what I am looking to do is:

myIdxs = [0, 3, 5]
myBools = [1, 0, 0, 1, 1, 1, 0, 1, 0, 1] 

and change myBools to:

myBools = [0, 0, 0, 0, 1, 0, 0, 1, 0, 1]

I've tried:

myBools = [myBools[i] for i in myIdx == 0]

But this does not give me the desired output.

lo_rabb
  • 109
  • 2
  • 10
  • We index starting from `0` and so shouldn't it be `myBools = [0,1,1,0,1,1]` assuming we are switching every `0` to a `1` and vice versa? How do you get `myBools = [1,0,0,1,0,0]`? – Teodorico Levoff Jun 20 '16 at 17:43
  • My apologies, I was not clear and did not keep things straight. I have edited the question with the correct index from 0 – lo_rabb Jun 20 '16 at 17:50
  • Unclear again, Shouldn't the output according to your logic be `[1, 0, 0, 1, 0, 1, 0, 0, 0, 0]`? – Bhargav Rao Jun 20 '16 at 17:51
  • I want to change the values of myBools to 0 at the indices given by myIndxs. – lo_rabb Jun 20 '16 at 17:58

3 Answers3

3

I hope this works (not sure what you need):

myIdxs = [0, 3, 5]
myBools = [1, 1, 1, 1, 1, 0]

myBools = [myBools[i] if i in myIdxs else 0
        for i in xrange(len(myBools))]

>>> print myBools
[1, 0, 0, 1, 0, 0]
th3an0maly
  • 3,360
  • 8
  • 33
  • 54
1

Poorly worded question, but here are two answers, both are extremely simple and straightforward, and don't required complex list comprehension.

If you want to change the bit to the opposite value

    myIdxs = [0, 3, 5]
    myBools = [1, 0, 0, 1, 1, 1, 0, 1, 0, 1]

    for i in myIdxs:
        myBools[i] ^= 1  # Bitwise operator flips the bit

    print(myBools)

If you want to change the bit to zero.

    myIdxs = [0, 3, 5]
    myBools = [1, 0, 0, 1, 1, 1, 0, 1, 0, 1]

    for i in myIdxs:
        myBools[i] = 0  # Sets bit to zero

    print(myBools)

Output

The output is actually the same for both, given the input, but don't let that fool you they do two very different things.

[0, 0, 0, 0, 1, 0, 0, 1, 0, 1]
[0, 0, 0, 0, 1, 0, 0, 1, 0, 1]
Chris
  • 15,819
  • 3
  • 24
  • 37
  • 1
    Sorry for the confusion, I will try to be more clear in the future. I was trying to convey the latter, and your solution worked. Thanks for your insight and help – lo_rabb Jun 20 '16 at 18:12
0

Try using list comprehension with if-else statement.

[myBools[i] if i in myIdxs else 0 for i in range(len(myBools))]

Output

[1, 0, 0, 1, 0, 0]
Hassan Mehmood
  • 1,414
  • 1
  • 14
  • 22