How do I take a list and print all of the content in a random order, printing each exactly one time in python?
本问题已经有最佳答案,请猛点这里访问。
这就是我所拥有的:
1 2 3 4 5 6 | >>> 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)] = '' ... |
但当我运行它时,
1 2 3 4 5 6 7 | 5.6 1 5.6 8 >>> |
我不希望它随机打印每个内容的数量,我希望它以随机顺序一次性打印所有内容。为什么是印刷空间?
试试这个:
1 2 3 4 5 | 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) |
1 2 3 4 | list = [1, 6, 7] random.shuffle(list) for k in range(1,len(list)+1): print list[k] |
1 2 3 4 5 6 | import random chars = ['s', 'p', 'a', 'm'] random.shuffle(chars) for char in chars: print char |
不过,这会随机化列表。
请参见以下链接:在python中随机播放和重新随机播放列表?
1 2 3 4 5 6 | from random import shuffle x = [[i] for i in range(10)] shuffle(x) print x |
这是您的代码的有效版本。
1 2 3 4 5 6 7 | 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]='' |
在