[英]Create an array according to index in another array in Python
I have an array like this: 我有一个像这样的数组:
X= [[1,2,3],
[3,2,1],
[2,1,3]]
Now I want to create another array Y. The elements in Y should take value 1 at positions where elements in X equal 2, otherwise they should take value 0. In this example, Y should equal to 现在,我要创建另一个数组Y。Y中的元素在X中的元素等于2的位置处应取值为1,否则它们应取值为0。在此示例中,Y应等于
Y=[[0,1,0],
[0,1,0],
[1,0,0]]
This would be greatly facilitated (and sped up) by using numpy
: 使用
numpy
可以大大方便(并加快):
import numpy as np
Y = (np.array(X) == 2).astype(int)
>>> Y
array([[0, 1, 0],
[0, 1, 0],
[1, 0, 0]])
您可以像这样使用列表理解:
Y = [[int(i == 2) for i in l] for l in X]
Y = [[1 if i==2 else 0 for i in row] for row in X]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.