[英]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.