這是我的代碼的一部分:
i = int(input("length of speech: " ))
b = 0
while b < i:
print(random.choice(uppercase) " ", end = "")
b = 1
請解釋我如何在列印后洗掉該串列中的一個專案
uj5u.com熱心網友回復:
如果你想用回圈來做這件事,你肯定有正確的想法。
uppercase = [...] # your list goes here
while len(uppercase) > 0:
i = random.randint(0, len(uppercase)) # Pick a random index in the list
print(uppercase[i]) # Print out the corresponding element
del uppercase[i] # Delete the element from the list and start again
uj5u.com熱心網友回復:
您應該能夠使用random.sample, 無需更換即可采樣:
請參閱:https ://docs.python.org/3/library/random.html#random.sample
由于random.sample將繪制次數作為輸入,您將i同時繪制所有字母,即您不再使用回圈。正如有些人所說,這也使事情變得更加“pythonic”。
將所有內容放在一起,您的示例將如下所示:
import random
import string
uppercase = string.ascii_uppercase
i = int(input("length of speech: " ))
print(" ".join(random.sample(uppercase, i)))
i請注意,如果大于大寫的長度,則會引發錯誤,這是應該的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/439252.html
標籤:Python python-3.x 列表
