具有空(或无)元素的随机播放列表 [英] Shuffle list with empty (or None) elements

查看:64
本文介绍了具有空(或无)元素的随机播放列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些列表,其值可以为空[]或NoneType

I've got some list of lists and it values can be empty [] or NoneType

lst = [[[]], [1, None], 2, [[], 3], 4]

我需要将它们随机化.例如,要获取 [[1,None],4,2,[[],3],[[]]] .

And I need to randomise them. To get [[1, None], 4, 2, [[], 3], [[]]], for example.

但是,如果我使用shuffle(lst),我会遇到一个例外:

But if I use shuffle(lst) I've got an exception:

TypeError: 'NoneType' object is not iterable

UPD:我的错误是我尝试将结果放入变量

UPD: My mistake was that I try to put the result into variable

newLst = shuffle(lst)

这就是NoneType对象.

That's give NoneType object.

推荐答案

来自评论:

问题在于对 random.shuffle 有效.您试图遍历返回的值 None ,因为 shuffle 不返回任何内容并就地更改其参数.

The problem is in misunderstanding of how random.shuffle works. You've tried to iterate through the returned value which is None, because shuffle returns nothing and changes its argument in-place.

这是解决此问题的方法:

Here's how you can solve this problem:

lst = [[[]], [1, None], 2, [[], 3], 4]
shuffle(lst) # Don't capture the return value
# lst is now shuffled and you can put it into `for` loop:
for x in lst:
    # something

这篇关于具有空(或无)元素的随机播放列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆