我试图在Python中创建一个随机列表。每次运行代码时,列表中的随机单词都会按顺序出现。我想做的是:
import random
numSelect = 0
list = ['thing1', 'thing2', 'thing3', 'thing4', 'thing5']
for i in range(random.randint(1, 3)):
rThing = random.choice(list)
numSelect = numSelect + 1
print(numSelect, '-' , rThing)
目标是要求用户从将要显示的列表中选择一些内容。下面是我想要的输出示例:
1 - thing4
2 - thing2
Which one do you choose?:
(User would type '2')
*output of thing2*
可以使用random.sample
从原始列表中获取子集。
然后可以使用enumerate()
对它们进行编号,并使用input
询问输入。
import random
all_choices = ["thing1", "thing2", "thing3", "thing4", "thing5"]
n_choices = random.randint(1, 3)
subset_choices = random.sample(all_choices, n_choices)
for i, choice in enumerate(subset_choices, 1):
print(i, "-", choice)
choice_num = 0
while not (1 <= choice_num <= len(subset_choices)):
choice_num = int(
input("Choose (%d-%d):" % (1, len(subset_choices)))
)
choice = subset_choices[choice_num - 1]
print("You chose", choice)
问题内容: 我正在使用PHP和MySQL创建一个简单的Web应用程序。在其中,我需要以随机顺序从表中随机选择一小组行。如何使用MySQL实现此类目标? 问题答案: SELECT * FROM table ORDER BY RAND() LIMIT 10;
如何从列表中随机选择Kotlin科特林的颜色?我找不到任何与这个话题相关的东西...< br >谢谢。
问题内容: 我需要输出: …,并且应该有一个包含4或5个链接的列表,这些链接指向实际的背景图片以供选择。我该如何使用SASS? 问题答案: Sass的最新版本(v3.3.0)添加了新功能。如果将其与图像列表(以及少量的变量插值)混合使用,则每次编译Sass时,CSS都会带有随机选择的背景图像。例: 如上所述,随机值仅在 编译Sass 时才会更改,而不一定在每次访问页面时更改。
问题内容: 如何从Java列表中随机选择一个项目?例如我有 等等…。如何使用 问题答案: 像这样吗
问题内容: 假设我有以下列表: 从此列表中随机检索项目的最简单方法是什么? 问题答案: 采用 对于加密安全的随机选择(例如,用于从单词列表生成密码短语),请使用 secrets是Python 3.6中的新功能,在旧版本的Python上,你可以使用此类:
问题内容: 我可以使用列出所有组合, 但这通常会很大。 给定和,我如何在不首先构建大量列表的情况下随机地均匀选择组合? 问题答案: 来自http://docs.python.org/2/library/itertools.html#recipes