我想用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
请求输入。你知道吗您可以先无序排列列表,然后为列表中的每个项目分配一个数字到字典:
使用字典理解的相同代码:
然后,您就有了一个键为0的字典(如果您想从1开始枚举,只需设置
enumerate(list, start=1)
),并从列表中随机排序项。你知道吗字典本身并不是真正必要的,因为无序列表中的每一项都已经有了一个位置。但我还是推荐它,这是一个不用动脑筋的建议。你知道吗
然后可以这样使用dict:
如果我理解正确的话,你的主要问题是列出列表中的所有项目,对吗?你知道吗
要方便地显示列表中的所有项目,然后用他们选择的内容进行响应,此代码应该可以工作。你知道吗
或者将最后一个print语句更改为您需要程序对用户输入执行的任何操作
UI
。你知道吗相关问题 更多 >
编程相关推荐