列表列表中元素的排列(permutation of elements inside the list of list)

编程入门 行业动态 更新时间:2024-10-25 02:18:52
列表列表中元素的排列(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.

更多推荐

本文发布于:2023-08-07 12:24:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464272.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:排列   元素   列表   列表中   list

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!