0
import numpy as np
data = np.array([[2,0,1,2,0],[0,1,2,0,1],[2,0,1,2,2]])

I require the following threes as separate variables

class0 = np.where(data==0)
class1 = np.where(data==1)
class2 = np.where(data==2)

I knew how to write them in three lines as above. However, what is the Pythonic way to do it using the examples below:

classes = ['class0', 'class1', 'class2']
values =[0,1,2]

for x, y in zip(classes, values):
    x = np.where(data == y)
    print x

HERE how can I name the answers resulted by x as class0,class1,class2???

0

2 Answers 2

1

Dictionary:

classes = ['class0', 'class1', 'class2']
values =[0,1,2]
output = {} #create a dictionary instance

for x, y in zip(classes, values):
    output[x] = np.where(data == y) #use the class name as the dictionary key
Sign up to request clarification or add additional context in comments.

Comments

1

Or you can do this if you really want three variables instead of a dictionary:

class0, class1, class2 = [np.where(data == i) for i in range(0, 3)]

This does not fit in the example you gave in the question though.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.