从随机生成的列表中选择-python

从随机生成的列表中选择-python,python,list,random,Python,List,Random,我试图在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(nu

我试图在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)
随机导入
所有选项=[“thing1”、“thing2”、“thing3”、“thing4”、“thing5”]
n_choices=random.randint(1,3)
子集_选项=随机.sample(所有_选项,n_选项)
对于i,枚举中的选择(子集_选择,1):
打印(i、“-”选项)
选择数=0

而不是(1您可以先洗牌列表,然后为列表中的每个项目分配一个数字到字典:

from random import shuffle

random_dict = {}
list = ['thing1', 'thing2', 'thing3', 'thing4', 'thing5']

shuffle(list)

for number, item in enumerate(list):
    random_dict[number] = item
使用字典理解的相同代码:

from random import shuffle

list = ['thing1', 'thing2', 'thing3', 'thing4', 'thing5']
shuffle(list)
random_dict = {number: item for number, item in enumerate(list)}
然后您就有了一个键为0的字典(如果您想从1开始枚举,只需设置
enumerate(list,start=1)
)并从列表中随机排列项目

字典本身并不是真正必要的,因为无序列表中的每一项都已经有了位置。但我还是推荐它,它是一个不需要动脑筋的工具

然后,您可以这样使用dict:

for k, v in random_dict.items():
    print("{} - {}".format(k, v))

decision = int(input("Which one do you choose? "))
print(random_dict[decision])

如果我理解正确,您的主要问题是列出列表中的所有项目是否正确

为了方便地显示列表中的所有项目,然后用他们选择的内容进行响应,此代码应该可以工作

list = ['thing1', 'thing2', 'thing3', 'thing4', 'thing5']
for i in range(len(list)):
    print(str(i)+": "+list[i])
UI = input("Make a selection: ")
print("You selected: "+list[int(UI)])

或者将最后一条打印语句更改为您需要程序对用户输入执行的任何操作。
UI

可能重复您想通过三个步骤执行此操作:创建一个字典,将其显示给用户,然后在该字典中查找他们的输入以获得他们的选择。@PatrickHaugh此处不需要dict-列表允许索引ed access。您好,欢迎访问该网站!我已经整理了您帖子中的语言,如果您对我的更改不满意,请随时重新编辑。