如何在python中随机打印列表中的元素? [英] How can a print elements in a list randomly in python?
问题描述
我有一个列表,我想按随机顺序打印.这是我到目前为止编写的代码:
随机导入words=["python","java","constant","immutable"]因为我的话:打印(我,结束=")input("") #停止窗口关闭
我尝试了多种方法来随机打印它们,例如创建一个变量,只随机选择其中一个,然后随机删除.然后我会重复这个步骤,直到它们都被删除并在另一个变量中.然后我会将变量放在一个列表中,然后将它们打印出来.尽管如此,这一直在产生错误.有没有其他方法可以做到这一点?
使用 random.shuffle()
原地打乱列表:
随机导入words = ["python", "java", "constant", "immutable"]random.shuffle(words)打印(*字)输入('')
演示:
<预><代码>>>>随机导入>>>words = ["python", "java", "constant", "immutable"]>>>random.shuffle(words)>>>字['python'、'java'、'常量'、'不可变']如果你想保留words
(保持顺序),你可以使用带有随机键的sorted()
来返回一个新的随机列表:
words = ["python", "java", "constant", "immutable"]print(*sorted(words, key=lambda k: random.random()))
这使 words
保持不变:
I've got a list which I want to print in random order. Here is the code I've written so far:
import random
words=["python","java","constant","immutable"]
for i in words:
print(i, end=" ")
input("") #stops window closing
I've tried a variety of things to print them out randomly, such as making a variable which selects only one of them randomly and then deleting the randomly. I would then repeat this step until they are all deleted and within another variable. Then I would put the variables in a list then print them out. This kept on generating errors though. Is there another way this can be done?
Use random.shuffle()
to shuffle a list, in-place:
import random
words = ["python", "java", "constant", "immutable"]
random.shuffle(words)
print(*words)
input('')
Demo:
>>> import random
>>> words = ["python", "java", "constant", "immutable"]
>>> random.shuffle(words)
>>> words
['python', 'java', 'constant', 'immutable']
If you wanted to preserve words
(maintain the order), you can use sorted()
with a random key to return a new randomized list:
words = ["python", "java", "constant", "immutable"]
print(*sorted(words, key=lambda k: random.random()))
This leaves words
unaltered:
>>> words = ["python", "java", "constant", "immutable"]
>>> sorted(words, key=lambda k: random.random())
['immutable', 'java', 'constant', 'python']
>>> words
['python', 'java', 'constant', 'immutable']
这篇关于如何在python中随机打印列表中的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!