Python 随机播放列表子列表的内容

Python shuffle content of sublists of a list

我在 python 中有一个列表列表:l = [ [1,2,3], [4,5,6], [7,8,9] ] 我想随机排列每个子列表。我怎样才能做到这一点?

请注意,在打乱子列表的内容时应保留子列表的顺序。这与之前的问题不同,例如,顺序打乱,内容保留。

我试过以下方法:

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)    

您不需要第 4 行的 "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) 

shuffle 就地工作,returns 什么都没有,所以使用:

random.shuffle(x)
for i in x:
    random.shuffle(i)
print(x)

您可以像这样尝试另一个名为 sample 的函数。我使用 python 3.6.

来自随机导入* x=[样本(i, len(i)) for i in x] 洗牌(x)

非常简单!虽然很容易解决,但是你可以试试别的功能