Shuffle list with empty (or None) elements [closed]

时光怂恿深爱的人放手 提交于 2021-01-29 04:52:22

问题


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

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

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

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

TypeError: 'NoneType' object is not iterable

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

newLst = shuffle(lst)

That's give NoneType object.


回答1:


From the comments:

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



回答2:


You want to make sure you shuffle in place before print or assignment.

>>> from random import shuffle
>>> lst = [[[]], [1, None], 2, [[], 3], 4]
>>> shuffle(lst)
>>> print(lst)
[2, 4, [[], 3], [1, None], [[]]]



回答3:


Glad you found the answer (that random.shuffle modifies the list in-place and returns None) - however, if you wanted to leave the list unmodified and get a "shuffled" result, then:

import random
shuffled = sorted(lst, key=lambda L: random.random())

Will do that for you.



来源:https://stackoverflow.com/questions/23581292/shuffle-list-with-empty-or-none-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!