从元组生成二维布尔数组 [英] Generate a 2D boolean array from tuples
本文介绍了从元组生成二维布尔数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用显示True值索引的元组列表生成2D布尔数组?
How can I generate a 2D boolean array using a list of tuples that shows the indices of the True values?
例如,我具有以下元组列表:
For example I have the following list of tuples:
lst = [(0,1), (0, 2), (1, 0), (1, 3), (2,1)]
我要做的是,我首先生成一个False数组:
What I do is, I first generate an array of False's:
arr = np.repeat(False, 12).reshape(3, 4)
然后,遍历列表以分配True值:
Then, iterate over the list to assign True values:
for tup in lst:
arr[tup] = True
print(arr)
array([[False, True, True, False],
[ True, False, False, True],
[False, True, False, False]], dtype=bool)
在我看来,这是一个常见的用例,所以我想知道是否有一个内置方法,没有循环.
It seems like a common use case to me so I was wondering if there is a built-in method for this, without the loops.
推荐答案
zip(*...)
是转置"列表列表(或元组)的便捷方法.并且A[x,y]
与A[(x,y)]
相同.
zip(*...)
is a handy way of 'transposing' a list of lists (or tuples). And A[x,y]
is the same as A[(x,y)]
.
In [397]: lst = [(0,1), (0, 2), (1, 0), (1, 3), (2,1)]
In [398]: tuple(zip(*lst)) # make a tuple of tuples (or lists)
Out[398]: ((0, 0, 1, 1, 2), (1, 2, 0, 3, 1))
In [399]: A=np.zeros((3,4),dtype=bool) # make an array of False
In [400]: A[tuple(zip(*lst))] = True # assign True to the 5 values
In [401]: A
Out[401]:
array([[False, True, True, False],
[ True, False, False, True],
[False, True, False, False]], dtype=bool)
这篇关于从元组生成二维布尔数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文