Python reshape a list to multidimensional list

后端 未结 3 1080
有刺的猬
有刺的猬 2021-01-06 00:16

I have a list that have different length in each dimension like below:

list1=[[2,3,4],[1],[77,8,27,12],[25,15]]

and I have another list wit

相关标签:
3条回答
  • 2021-01-06 00:21

    If you want to process them in a loop, you can just do this:

    list1=[[2,3,4],[1],[77,8,27,12],[25,15]]
    
    list2=["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
    
    last = 0
    
    for ele in list1:
        print(ele, list2[last : last + len(ele)])
        last += len(ele)
    

    Result:

    ([2, 3, 4], ['a', 'b', 'c'])
    ([1], ['d'])
    ([77, 8, 27, 12], ['e', 'f', 'g', 'h'])
    ([25, 15], ['i', 'j'])
    
    0 讨论(0)
  • 2021-01-06 00:28

    Flattening list1 to match list2 is easy—either just use itertools.chain.from_iterable(list)), or flat1 = [elem for sublist in list1 for elem in sublist], or the various other options in this question.

    Going the other way is a bit more complicated. But, rather than looking for a one-liner, let's just do it explicitly: Create an iterator over list2, and pull elements off it as needed:

    def zipstructured(list1, list2):
        iter2 = iter(list2)
        for sublist1 in list1:
            sublist2 = list(itertools.islice(iter2, len(sublist1)))
            yield sublist1, sublist2
    

    Now you can just do this:

    >>> list1=[[2,3,4],[1],[77,8,27,12],[25,15]]
    >>> list2=['a','b','c','d','e','f','g','h','i','j']
    >>> for sub1, sub2 in zipstructured(list1, list2):
    ...     print(sub1, sub2)
    [2, 3, 4] ['a', 'b', 'c']
    [1] ['d']
    [77, 8, 27, 12] ['e', 'f', 'g', 'h']
    [25, 15] ['i', 'j']
    
    0 讨论(0)
  • 2021-01-06 00:33

    Here's a kind of cute way.

    list1 = [[2,3,4],[1],[77,8,27,12],[25,15]]
    list2 = list("abcdefghij")
    
    list2_iterator = iter(list2)
    list2_reshaped = [[next(list2_iterator) for _ in sublist] for sublist in list1]
    
    print(list2_reshaped)
    
    Out: [['a', 'b', 'c'], ['d'], ['e', 'f', 'g', 'h'], ['i', 'j']]
    

    I don't know if it's possible with pure comprehensions.

    0 讨论(0)
提交回复
热议问题