首页 > 解决方案 > 如何从选择的嵌套列表中获得随机选择?

问题描述

我有一个简单的嵌套变量列表,其中包含 6 个玩家姓名。如下所示。

player_options = [[person_1, person_2],[person_3, person_4], [person_5, person_6]]

我想得到的是来自第一个嵌套的随机变量,然后是第二个或第三个嵌套的随机变量。我目前可以从第一个巢和第二个第三个中随机选择一个,但不是第二个第三个?

我目前拥有的代码是

pair_1 = random.choice(player_options[0]) + random.choice(player_options[1]) 

我将如何从嵌套 [0] 中获得随机选择以及从嵌套 [1] 或 [2] 中获得随机选择?

如果您需要更多信息,请告诉我!

谢谢 :)

标签: pythonpython-3.xlistnested-lists

解决方案


关于什么

biggest_index = len(player_options) - 1 # Get the biggest/last index
second_choice = random.randint(1,biggest_index) # Chose a random index between the second (1) and the last one
pair_1 = random.choice(player_options[0]) + random.choice(player_options[second_choice]) 

或者通过第二次使用选择功能来做到这一点:

second_choice = random.choice(player_options[1:]) # Choose random element after first index
pair_1 = random.choice(player_options[0]) + random.choice(second_choice) 

推荐阅读