简体   繁体   English

如果二维列表中有空元素,则将 Python 二维列表转换为 3D 列表

[英]convert a Python 2D list to 3D list, if there are empty elements in 2D list

Using Python3 with or without NumPy, how can I convert在有或没有 NumPy 的情况下使用 Python3,我该如何转换

a =[[1,2],[0,1],[],[2,2],[],[2,13],[1,4],[6,1],[],[2,7]]

(with respect to its empty elements), to (关于它的空元素),到

b=[[[1, 2], [0, 1]], [[2, 2]], [[2, 13], [1, 4], [6, 1]], [[2, 7]]] 

I appreciate any help on this.我很感激这方面的任何帮助。

Thanks谢谢

Please try the script below:请尝试以下脚本:

a =[[],[1,2],[0,1],[],[2,2],[],[2,13],[1,4],[6,1],[],[2,7]]
newlist=[]
temp=[]
for element in a:
    if element: # if element is not empty add to temp
        temp.append(element)
    elif temp: # if element is empty and temp is not empty add temp to newlist
        newlist.append(temp)
        temp=[]
if temp: # if temp is not empty add to newlist
    newlist.append(temp)        
print(newlist) 

Using itertools's groupby使用itertools's groupby

from itertools import groupby

lst = []

for i, g in groupby(a, key=lambda x: len(x) >= 1):
    grp = list(g)
    if i and len(grp) >= 1:
        lst.append(grp)

lst:第一:

[[[1, 2], [0, 1]], [[2, 2]], [[2, 13], [1, 4], [6, 1]], [[2, 7]]]

You can do this你可以这样做

def func(a):
    b = [[]]
    for i in (a): # iterate over a
        if i: # if ith element is not empty list
            b[-1].append(i) # add it to the latest list in b
        else: # otherwise append new list to b
            b.append([])
    return b

OR Similarly,或类似地,

def func(a):
    b, c = [], []
    c = [b[-1].append(i) for i in ([[]] + a ) if (i or b.append([]))]
    return b

Both follow basically the same process,两者都遵循基本相同的过程,

2nd snippet wastes an extra variable第二个片段浪费了一个额外的变量

You can try this.你可以试试这个。

from collections import deque

a = [[1,2],[0,1],[],[2,2],[],[2,13],[1,4],[6,1],[],[2,7]]

d = deque(a)
if d[0] == []:
    d.popleft()
if len(d) > 0:
    if d[-1] == []:
        d.pop()
tmp = []; b = []
for x in d:
    if x == []:
        b.append(tmp)
        tmp = []
    else:
        tmp.append(x)
b.append(tmp)     
print(b)


 

outputs:输出:

[[[1, 2], [0, 1]], [[2, 2]], [[2, 13], [1, 4], [6, 1]], [[2, 7]]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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