![](/img/trans.png)
[英]How to print a random string from a list, when given an input? (Python)
[英]how to print random string in list
a = ['hello','chicken','world']
import random
a = random(a)
print (a) #trying to print them in random order.
我將如何以隨機順序打印它們? 它給我一個錯誤:“類型錯誤:'模塊'對象不可調用”。 還可以從列表中打印一個單詞,然后問用戶接下來是什么? 並檢查用戶是否正確,然后繼續瀏覽整個列表。
使用random.shuffle()
將您的列表隨機排列。 例如
>>> a = ['hello','chicken','world']
>>> import random
>>> a
['hello', 'chicken', 'world']
>>> random.shuffle(a)
>>> a
['chicken', 'world', 'hello']
>>> random.shuffle(a)
>>> a
['hello', 'world', 'chicken']
這是因為您的調用random
是模塊而不是方法。 您可能要調用random.choice
參見random.choice
import random
a = ['hello','chicken','world']
random.shuffle(a)
print "first element is %s" %a[0]
for i in a[1:]:
guess = str(raw_input("Guess next item:")).strip()
if guess == i:
print "Correct"
else:
print "Wrong it was: %s" %i
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.