从一个随机生成的列表中进行选择 - python
从一个随机生成的列表中进行选择 - 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 你选择哪个?: (用户输入'2') *输出thing2*
问题:从随机生成的列表中选择一个项目的原因是需要在列表中随机选择一个项目。
解决方法:首先对列表进行洗牌,然后为列表中的每个项目分配一个数字,并将它们存储在一个字典中。然后可以使用该字典来选择一个项目。
以下是解决方法的代码示例:
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)}
然后,可以使用该字典来进行选择:
for k, v in random_dict.items(): print("{} - {}".format(k, v)) decision = int(input("Which one do you choose? ")) print(random_dict[decision])
通过以上代码,我们得到了一个具有从0开始的键和随机顺序的项目的字典。虽然字典本身并不是必需的,因为洗牌后的列表中的每个项目已经有了位置,但仍建议使用字典,因为它更加简单明了。
以上就是从随机生成的列表中选择一个项目的原因以及解决方法。
在这段代码中,问题的出现主要是要从一个随机生成的列表中选择一个选项,并且需要用户输入来确定选择的选项。但是,代码中存在一些问题和需要解决的地方。
首先,代码使用了random.sample
函数从原始列表all_choices
中获取一个子集subset_choices
。然后,使用enumerate()
函数对子集中的选项进行编号,并使用input
函数要求用户输入选择的选项编号。然而,代码中存在一些问题和需要解决的地方。
问题1:代码中随机生成子集的长度,但是没有限制子集的最大长度,可能会导致选择过多的选项。
问题2:在要求用户输入选择的选项编号时,没有对用户的输入进行验证,可能会导致输入不合法的选项编号。
解决方法:
问题1的解决方法是在生成子集时,对子集的长度进行限制。可以使用random.randint
函数来生成一个介于1和3之间的随机数,并将其作为子集的长度。
n_choices = random.randint(1, 3)
问题2的解决方法是在要求用户输入选择的选项编号时,对输入进行验证。可以使用一个循环,直到用户输入合法的选项编号为止。循环条件是选项编号大于等于1且小于等于子集的长度。
choice_num = 0 while not (1 <= choice_num <= len(subset_choices)): choice_num = int( input("Choose (%d-%d):" % (1, len(subset_choices))) )
最后,输出用户选择的选项。
print("You chose", choice)
以上代码是一个从随机生成的列表中选择选项并获取用户输入的示例。通过限制子集的长度和验证用户输入的选项编号,可以确保代码的正常运行。
问题的出现原因:
问题是关于从随机生成的列表中进行选择的。主要问题是如何列出列表中的所有项。
解决方法:
为了方便地显示列表中的所有项,并且在用户进行选择后作出响应,可以使用以下代码:
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)])
或者将最后一个print语句改成你需要程序在用户输入`UI`后执行的任何操作。