列表列表中元素的排列(permutation of elements inside the list of list)
我有一个嵌套列表如下:
A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]我只需要对每个列表中的元素进行排序。
你知道我怎么能这样做吗?
I have a nested list as follows:
A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]I need to permute only the elements inside each list.
do you have any idea how can I do this?
最满意答案
要在列表random.shuffle中对每个子列表进行随机播放,您不能使用random.shuffle因为它可以在适当的位置使用。 您可以使用random.sample ,样本长度=列表长度:
import random A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] new_a = [random.sample(l,len(l)) for l in A] print(new_a)输出:
[[2, 1, 3], [5, 4, 6], [7, 9, 8]]如果您不想修改原始列表,该解决方案是最好的解决方案。 否则,在循环中使用shuffle ,因为其他人的回答也很好。
To shuffle each sublist in a list comprehension, you cannot use random.shuffle because it works in place. You can use random.sample with the sample length = the length of the list:
import random A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] new_a = [random.sample(l,len(l)) for l in A] print(new_a)an output:
[[2, 1, 3], [5, 4, 6], [7, 9, 8]]That solution is the best one if you don't want to modify your original list. Else, using shuffle in a loop as someone else answered works fine as well.
更多推荐
发布评论