我有一个项目要从一本作为圣诞礼物收到的书中完成(绝对初学者的Python编程,第三版):
创建一个以随机顺序打印单词列表的程序。该程序应打印所有单词,不要重复任何单词。
我创建了以下代码:
import random
words = ["Please", "Help", "Me", "Merry", "Christmas"]
for i in range(len(words)):
random_index = random.randrange(len(words))
print(words[random_index])
del words[random_index]
我想检查这段代码是否是最有效的方式,但是没有论坛可以检查,而是令人沮丧!
有更好的方法吗?干杯
答案 0 :(得分:8)
如何使用random.sample
:
>>> import random
>>> words = ["Please", "Help", "Me", "Merry", "Christmas"]
>>> random.sample(words, len(words))
['Merry', 'Me', 'Help', 'Please', 'Christmas']
或random.shuffle
如果可以修改原始列表:
>>> random.shuffle(words)
>>> words
['Me', 'Merry', 'Help', 'Please', 'Christmas']
答案 1 :(得分:2)
如果你只想使用本章所涉及的内容,那么这可能是一个解决方案:
import random
myList = ["create", "a", "program", "that", "prints"]
for i in range(len(myList)):
randomWord = random.choice(myList)
print(randomWord)
myList.remove(randomWord)
input("\nPress enter to exit.")
答案 2 :(得分:1)
import random
random.shuffle(words)
print words
Random是模块,它为您提供了一个名为shuffle()的内置方法,该方法可用于更改以任意随机顺序传递的list参数的元素。
答案 3 :(得分:1)
除了像其他人所建议的那样直接使用Python的sample
或shuffle
函数之外,你的解决方案工作得很好,但它有一个缺点就是清空原来的words
列表,这可能是不可取。
为此,以下内容同时进行并复制shuffle。
import random
words = ["Please", "Help", "Me", "Merry", "Christmas"]
# in-place or copy shuffle
def shuffle(in_words, copy=False):
in_words = in_words[:] if copy else in_words
for i in range(len(in_words)):
pos = random.randrange(len(in_words))
in_words[i], in_words[pos] = in_words[pos], in_words[i]
return in_words
# see if it works
print "unshuffled", words
print "shuffled %s (was: %s)" % (shuffle(words, copy=True), words)
print "in-place shuffled", shuffle(words)
答案 4 :(得分:0)
导入随机
words = ["Please", "Help", "Me", "Merry", "Christmas"]
for i in range(len(words)):
random_index = random.randrange(len(words))
print(words.pop(random_index))
答案 5 :(得分:0)
import random
words = ["Please", "Help", "Me", "Merry", "Christmas"]
wordsUsed = []
print()
while len(wordsUsed) != len(words):
choice = random.choice(words)
if choice not in wordsUsed:
print(choice)
wordsUsed.append(choice)
input("\nPress the enter key to exit..")
答案 6 :(得分:0)
随机导入 WORDS = [“喜悦”,“希望”,“善良”,“爱”,“耐心”,“奉献”] 已使用= [] 而WORDS: comp_choice = random.choice(WORDS) 如果未使用comp_choice: 打印(comp_choice,end =“”) used.append(comp_choice)
答案 7 :(得分:0)
不是很优雅,但是它仅使用了到目前为止本书中提到的方法。
import random
init_list = ["i", "need", "coffee", "break", "and", "to", "go", "home"]
new_list = []
for i in range(len(init_list)):
n = random.randint(len(init_list)-1)
new_list.append(init_list[n])
del init_list[n]
print(new_list)
input("Press Enter to exit")
答案 8 :(得分:-1)
list=["hello","bye","good night","welcome"]
new_list=[]
import random
while len(new_list)!=4:
word=random.choice(list)
if word not in new_list:
new_list.append(word)
else:
new_word.remove(word)
print(new_list)