Python将列表重塑为多维列表

时间:2018-08-26 19:43:19

标签: python python-3.x list multidimensional-array

我有一个列表,每个维度的长度都不同,如下所示:

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

还有另一个具有相同元素数量的列表,如:

list2=[a,b,c,d,e,f,g,h,i,j]

我想将我的list2重塑为list1,并在for循环中一起处理两个列表。

3 个答案:

答案 0 :(得分:3)

整理list1以匹配list2很容易-只需使用itertools.chain.from_iterable(list))flat1 = [elem for sublist in list1 for elem in sublist],或使用其他各种选项in this question

采用另一种方法会更加复杂。但是,与其寻找单一的行,不如直接做它:在list2上创建一个迭代器,并根据需要拉出元素:

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

现在您可以执行以下操作:

>>> 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']

答案 1 :(得分:3)

这是一种可爱的方式。

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']]

我不知道单纯的理解是否有可能。

答案 2 :(得分:1)

如果要循环处理它们,可以执行以下操作:

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)

结果:

([2, 3, 4], ['a', 'b', 'c'])
([1], ['d'])
([77, 8, 27, 12], ['e', 'f', 'g', 'h'])
([25, 15], ['i', 'j'])
相关问题