如何从 2D 列表中pythonically 选择一个随机索引,以便相应的元素匹配一个值? [英] How to pythonically select a random index from a 2D list such that the corresponding element matches a value?

查看:66
本文介绍了如何从 2D 列表中pythonically 选择一个随机索引,以便相应的元素匹配一个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个布尔值的二维列表.我想从值为 False 的列表中选择一个随机索引.例如,给定以下列表:

[[真,假,假],[真实,真实,真实],[假,真,真]]

有效的选择是:[0, 1][0, 2][2, 0].

我可以保留一个有效索引的列表,然后使用 random.choice 从中进行选择,但保留一个变量并在每次底层列表仅针对此更改时更新它似乎是不合逻辑的目的.

如果你的答案跑得很快,就加分.

解决方案

我们可以使用 oneliner 像:

将 numpy 导入为 np从随机导入选择选择(np.argwhere(~a))

使用 a 布尔数组.

其工作原理如下:通过使用~a,我们否定数组的元素.接下来我们使用 np.argwhere 来构造一个 k×2-array:一个数组,其中每一行都有两个元素:对于每个维度,对应的值具有作为值 False.

通过choice(..),我们选择了一个随机行.然而,我们不能直接使用它来访问元素.我们可以使用 tuple(..) 构造函数将其转换为元组:

<预><代码>>>>元组(选择(np.argwhere(~a)))(2, 0)

因此您可以使用以下命令获取元素:

t = tuple(choice(np.argwhere(~a)))在]

当然,这并不奇怪:

<预><代码>>>>t = 元组(选择(np.argwhere(~a)))>>>在]错误的

I have a 2D list of booleans. I want to select a random index from the the list where the value is False. For example, given the following list:

[[True, False, False],
 [True, True, True],
 [False, True, True]]

The valid choices would be: [0, 1], [0, 2], and [2, 0].

I could keep a list of valid indices and then use random.choice to select from it, but it seems unpythonic to keep a variable and update it every time the underlying list changes for only this one purpose.

Bonus points if your answer runs quickly.

解决方案

We can use a oneliner like:

import numpy as np
from random import choice

choice(np.argwhere(~a))

With a the array of booleans.

This works as follows: by using ~a, we negate the elements of the array. Next we use np.argwhere to construct a k×2-array: an array where every row has two elements: for every dimension the value such that the corresponding value has as value False.

By choice(..) we thus select a random row. We can however not use this directly to access the element. We can use the tuple(..) constructor to cast it to a tuple:

>>> tuple(choice(np.argwhere(~a)))
(2, 0)

You can thus fetch the element then with:

t = tuple(choice(np.argwhere(~a)))
a[t]

But of course, it is not a surprise that:

>>> t = tuple(choice(np.argwhere(~a)))
>>> a[t]
False

这篇关于如何从 2D 列表中pythonically 选择一个随机索引,以便相应的元素匹配一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆