Python洗牌lis子列表的内容

2024-04-23 20:50:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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)    

Tags: the方法import内容列表for顺序random
3条回答

shuffle就地工作,不返回任何内容,因此请使用:

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

您可以尝试另一个类似于sample的函数。我使用python3.6。在

从随机导入* x=[样品(i,len(i)),用于x中的i] 随机播放(x)

这很简单!虽然很容易解决,但您可以尝试其他函数。在

你不需要第四行的“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) 

根据评论中的建议,这里有一个更新的版本:

^{pr2}$

相关问题 更多 >