如何获取一个列表并以随机顺序打印所有内容,在python中只打印一次?

如何获取一个列表并以随机顺序打印所有内容,在python中只打印一次?,python,python-2.7,for-loop,random,Python,Python 2.7,For Loop,Random,这就是我所拥有的: >>> import random >>> chars = [1, 6, 7, 8, 5.6, 3] >>> for k in range(1, len(chars)+1): ... print random.choice(chars) ... chars[random.choice(chars)] = '' ... 但当我运行它时 5.6 1 5.6 8 >>> 我不希望它随机打印每一

这就是我所拥有的:

>>> import random
>>> chars = [1, 6, 7, 8, 5.6, 3]
>>> for k in range(1, len(chars)+1):
...   print random.choice(chars)
...   chars[random.choice(chars)] = ''
...
但当我运行它时

5.6
1

5.6

8
>>> 

我不希望它随机打印每一个内容,我希望它以随机顺序打印所有内容一次。为什么要打印空格?

这是您的代码的工作版本

import random
chars = [1, 6, 7, 8, 5.6, 3]
for k in range(1, len(chars)+1):
    thechar = random.choice(chars)
    place = chars.index(thechar)
    print thechar
    chars[place:place+1]=''
当您在
打印random.choice(chars)
chars[random.choice(chars)]=''
中两次执行random.choice时,它将从
chars
中选择另一个随机选项。相反,请将
random.choice
设置为某个值,以便稍后调用。即使您已经这样做了,当您设置
chars[random.choice(chars)]='
,它只是将该点设置为
'
,它不会删除它。因此,如果您的
random.choice
5.6
,那么
chars
列表将变成
[1,6,7,8',,3]
,而不是
[1,6,7,8,3]
。为此,您必须保存字符的位置,然后执行
chars[place:place+1]
。最后,由于的
语法,您必须执行
len(chars)+1
,这样它只会进入
len(chars)
查看以下链接:

试试这个:

import random
chars = [1, 6, 7, 8, 5.6, 3]
r = chars [:] #make a copy in order to leave chars untouched
random.shuffle (r) #shuffles r in place
print (r)

这将使列表随机化。

您需要
random.shuffle
。见文件:
list = [1, 6, 7]
random.shuffle(list)
for k in range(1,len(list)+1):
    print list[k]
import random
chars = ['s', 'p', 'a', 'm']

random.shuffle(chars)
for char in chars:
    print char
list = [1, 6, 7]
random.shuffle(list)
for k in range(1,len(list)+1):
    print list[k]