【发布时间】:2018-01-11 10:49:47
【问题描述】:
我在 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)
【问题讨论】:
-
@sujittiwari:这根本不是这个问题的重复。
-
@UbdusSamad:这与 sujittiwari 提出的问题完全相同。而且它不是重复的。
-
我的道歉,看起来几乎一样。 @TimPietzcker
标签: python list random shuffle nested-lists