python - 如何从选择的嵌套列表中获得随机选择?
问题描述
我有一个简单的嵌套变量列表,其中包含 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] 中获得随机选择?
如果您需要更多信息,请告诉我!
谢谢 :)
解决方案
关于什么
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)
推荐阅读
- jquery - 样式引导程序选择不同的“占位符”
- r - 如何使用 ifelse 选择多个类别
- android - Android 和 iOS 上的 SVG 资源
- javascript - 使用 Jquery 根据输入编写完整的公式
- java - 使用 Cargo 插件将 Web 应用程序部署到远程服务器
- xcode - VideoCloudSamplePlayer iOS 示例应用程序视频再现
- c# - 使用 DbConnection 作为属性,只有 get 或 as 方法
- sql - 我有一个名为 authorsjson 的 JSON 列,其中包含 json 数据。我想找到名称以给定字符串开头的所有用户
- go - 按 mime 类型获取文件扩展名
- java - 不正确地显示图表