How to divide python list into sublists of unequal length?

后端 未结 5 1474
情书的邮戳
情书的邮戳 2021-01-25 22:30

I am trying to divide a list of elements which are comma separated into chunks of unequal length. How can I divide it?

list1 = [1, 2, 1]
list2 = [\"1.1.1.1\", \"         


        
5条回答
  •  攒了一身酷
    2021-01-25 23:29

    You can use itertools.islice for this too. It's efficient and easy to read:

    def unequal_divide(iterable, chunks):
        it = iter(iterable)
        return [list(islice(it, c)) for c in chunks]
    

    Then to use it:

    >>> list1 = [1, 2, 1]
    >>> list2 = ["1.1.1.1", "1.1.1.2", "1.1.1.3", "1.1.1.4"]
    >>> unequal_divide(list1, list2)
    [['1.1.1.1'], ['1.1.1.2', '1.1.1.3'], ['1.1.1.4']]
    

    Or as a generator:

    def unequal_divide(iterable, chunks):
        it = iter(iterable)
        for c in chunks:
            yield list(islice(it, c))
    

    In use:

    >>> list(unequal_divide(list1, list2))
    [['1.1.1.1'], ['1.1.1.2', '1.1.1.3'], ['1.1.1.4']]
    

    This is also implemented in more-itertools.split_at. See here for their source code which is almost identical minus allowing no chunks to be provided which is weird.

提交回复
热议问题