我在python:l = [ [1,2,3], [4,5,6], [7,8,9] ]中有一个列表,我想对每个子列表进行混洗。我如何才能做到这一点?
请注意,在对子列表的内容进行混洗时,应保留子列表的顺序。这与之前的问题不同,例如this question,在这些问题中,顺序被打乱,内容被保留。
我尝试过以下几种方法:
import random
x = [ [1,2,3], [4,5,6], [7,8,9] ]
random.shuffle(x) # This shuffles the order of the sublists,
# not the sublists themselves.
x = [ random.shuffle(sublist) for sublist in x ] # This returns None
# for each sublist.
print(x) 发布于 2018-01-11 18:51:53
你不需要在第四行加上"x =“。
代码:
import random
x = [ [1,2,3], [4,5,6], [7,8,9] ]
random.shuffle(x) # This shuffles the order of the sublists,
# not the sublists themselves.
[ random.shuffle(sublist) for sublist in x ] # This returns None
# for each sublist.
print(x) 根据评论中的建议,这里有一个更新的版本:
import random
x = [ [1,2,3], [4,5,6], [7,8,9] ]
random.shuffle(x)
for sublist in x:
random.shuffle(sublist)
print(x) 发布于 2018-01-11 18:57:18
shuffle就地工作,不返回任何内容,因此使用:
random.shuffle(x)
for i in x:
random.shuffle(i)
print(x)发布于 2018-01-11 19:39:33
您可以尝试另一个名为sample的函数,如下所示。我使用的是python 3.6。
从随机导入* x=sample(i,len(i))中获取i in x shuffle(x)
这很简单!虽然它很容易解决,但你可以尝试另一个函数。
https://stackoverflow.com/questions/48205282
复制相似问题