繁体   English   中英

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

[英]Choosing from a randomly generated list - python

我正在尝试在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)

您可以先随机播放列表,然后为列表中的每个项目分配一个数字:

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) ),然后从列表中随机排序各项。

字典本身并不是真正必要的,因为改组列表中的每个项目都已经有位置。 但是无论如何我还是推荐它,这很容易。

然后,您可以像这样使用字典:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM