Logical indexing with lists

I have a program that I am viewing, and with this section

temp = [1,2,3,4,5,6] temp[temp!=1]=0 print temp 

What if run gives the result:

 [1, 0, 3, 4, 5, 6] 

I need help understanding what is going on in this code, which leads to this result.

+5
source share
3 answers

As already explained, you set the second element using the result of comparing with a list, which returns True / 1 as bool is a subclass of int . You have a list, not a numpy array, so you need to iterate over it if you want to change it, which you can do with list comprehension using if / else logic:

 temp = [1,2,3,4,5,6] temp[:] = [0 if ele != 1 else ele for ele in temp ] 

What will give you:

 [1, 0, 0, 0, 0, 0] 

Or using a generator expression:

 temp[:] = (0 if ele != 1 else ele for ele in temp) 
+3
source

temp in your example is list , which is clearly not equal to 1. Thus, the expression

  temp[temp != 1] = 0 

actually

 temp[True] = 0 # or, since booleans are also integers in CPython temp[1] = 0 

Convert temp to a NumPy array to get the broadcast behavior you need.

 >>> import numpy as np >>> temp = np.array([1,2,3,4,5,6]) >>> temp[temp != 1] = 0 >>> temp array([1, 0, 0, 0, 0, 0]) 
+7
source

If NumPy is not an option, use the list view to create a new list.

 >>> temp = [1,2,3,4,5,6] >>> [int(x == 1) for x in temp] [1, 0, 0, 0, 0, 0] 
+3
source

Source: https://habr.com/ru/post/1247437/


All Articles