从随机生成的列表中选择

2024-09-30 10:27:31 发布

您现在位置: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*

Tags: 代码import列表for顺序random单词list
3条回答

可以使用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)),并从列表中随机排序项。你知道吗

字典本身并不是真正必要的,因为无序列表中的每一项都已经有了一个位置。但我还是推荐它,这是一个不用动脑筋的建议。你知道吗

然后可以这样使用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)])

或者将最后一个print语句更改为您需要程序对用户输入执行的任何操作UI。你知道吗

相关问题 更多 >

    热门问题