【问题标题】:Python shuffle content of sublists of a listPython shuffle 列表子列表的内容
【发布时间】: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)    

【问题讨论】:

标签: python list random shuffle nested-lists


【解决方案1】:

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

【讨论】:

  • 虽然这可行,但仅将列表推导式用于其副作用是很丑陋的。一个合适的for 循环会好很多。
  • 你说得对。不过,通过仅删除 2 个字符来解决帖子是一个很酷的技巧。 :-)
【解决方案2】:

shuffle 在原地工作并且不返回任何内容,因此请使用:

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

【讨论】:

  • 您可以使用shuffled(x) 来返回列表,而不是就地改组。
  • @allo:shuffled 来自哪里?它当然不是 Python 内置的,也不是 Python 标准库的一部分。
  • Sorry shuffled 确实不在标准库中,而是这里代码库的一部分。我已经习惯了,因为它类似于 sorted,我认为它是 python 标准。
【解决方案3】:

您可以像这样尝试另一个名为 sample 的函数。我使用 python 3.6。

随机导入 * x=[样本(i, len(i)) for i in x] 洗牌(x)

这很容易!虽然很容易解决,但你可以试试其他功能。

【讨论】:

    猜你喜欢
    • 2015-04-12
    • 1970-01-01
    • 2013-09-12
    • 2016-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多