如何从嵌套列表中选择随机索引



示例:

a = [0, 1, 2]
b = [3, 4, 5]
c = [6, 7, 8]
exampleList = [a, b, c]

正如你所看到的,列表"exampleList"包含其他也是列表的变量,我的意图是从"exampleList"中获得一个随机索引,并从该随机索引中获得该列表中的一个随机指数(因此是从a、b或c中获得的随机指数)。

让变量randomIndex从列表中选择一个随机索引,randomSub从子列表中选择与随机索引选择的索引等效的随机索引。

我试过了:

exampleList[randomIndex][randomSub]

然而,这给了我以下错误:

IndexError:列表索引超出范围。

我也试过:

exampleList[randomIndex]

看看这是否至少有效,它确实有效,但它返回了整个列表,我确实预料到了,所以我的问题是,我如何从同样是随机选择的子列表中检索随机索引?请随意烹饪我,因为我是编程新手,但如果你要吐槽我,请给我有效的见解。

编辑:

在这种情况下,这些是进行随机选择的函数:randomIndex函数

randomSub函数(忽略末尾的[random_hint])

您可能想要的是random.choice,它直接从给定列表中给您一个随机项,而无需做额外的工作来找出有效索引是什么,选择一个,然后将其转换回一个项:

>>> a = [0, 1, 2]
>>> b = [3, 4, 5]
>>> c = [6, 7, 8]
>>>
>>> exampleList = [a, b, c]
>>> import random
>>> random.choice(exampleList)
[3, 4, 5]
>>> random.choice(exampleList)
[6, 7, 8]

因此,您可以在exampleList上调用random.choice一次,以随机获得abc中的一个,然后在您获得的任何列表上再次调用random.choice,如下所示:

>>> random.choice(random.choice(exampleList))
2
>>> random.choice(random.choice(exampleList))
7

如果您特别想要索引而不是值,则可以使用rangelen来获得给定列表的有效索引序列:

>>> random.choice(range(len(exampleList)))
2
>>> random.choice(range(len(exampleList)))
0

所以你可以做:

>>> randomIndex = random.choice(range(len(exampleList)))
>>> randomSub = random.choice(range(len(exampleList[randomIndex])))
>>> exampleList[randomIndex][randomSub]
3

这是与两个嵌套的CCD_ 10调用的更简单示例相同的有效结果。

最新更新