简体   繁体   中英

Python: sort a list of lists

I have a list which has nested lists. These nested lists are sentences. I want to randomize the order of sentences, but the random.shuffle() method does not supported nested lists.

[['A', 'B'],['C','D'],['E','F']]

I only want to reorder the sentences (randomly) not the words in the sentence, how can I achieve that?

shuffle is working fine for me.

>>>from random import shuffle
>>>l=[['a','b'],['c','d'],['e','f']]
>>>shuffle(l)
>>>l
[['c', 'd'], ['a', 'b'], ['e', 'f']]
>>>shuffle(l)
>>>l
[['c', 'd'], ['e', 'f'], ['a', 'b']]

This might help you as example

import random
def deep_shuffle_iter(i):
    try:
        map(shuffle_iter, random.shuffle(i))
    except TypeError: pass

It does shuffle of iters using recursion

eg

>>> asd = [[0,1],[2,3],[4]]
>>> shuffle_iter(asd)
>>> asd
[[4], [2, 3], [0, 1]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM