How can a print elements in a list randomly in pyt

2019-07-24 16:27发布

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?

4条回答
beautiful°
2楼-- · 2019-07-24 16:52

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

查看更多
【Aperson】
3楼-- · 2019-07-24 16:57
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楼-- · 2019-07-24 17:02

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']
查看更多
啃猪蹄的小仙女
5楼-- · 2019-07-24 17:04

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=" ")
查看更多
登录 后发表回答