How can a print elements in a list randomly in pyt

2019-07-24 16:32发布

问题:

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?

回答1:

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']


回答2:

Try this:

import random
words2 = words[::]
random.shuffle(words2)
for w in words2:
    print(w, end=" ")

Notice that I copied the original list first, in case you want to preserve it. If you don't mind shuffling it, this should do the trick:

import random
random.shuffle(words)
for w in words:
    print(w, end=" ")


回答3:

import random
random.choice([1,2,3])
#random element from the iterable 

hope it helps, random.choice() returns randomly chosen element from the list.



回答4:

If you really want to, you could use random.randint to pick a random integer, then print the word that corresponds with that integer.