[英]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)
您不需要在第四行使用“ 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
在原位工作,不返回任何内容,因此请使用:
random.shuffle(x)
for i in x:
random.shuffle(i)
print(x)
您可以尝试使用另一个名为sample的函数。 我使用python 3.6
来自随机导入* x = [x中的i的sample(i,len(i))] shuffle(x)
这很容易! 尽管很容易解决,但是您可以尝试其他功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.