[英]convert a Python 2D list to 3D list, if there are empty elements in 2D list
在有或沒有 NumPy 的情況下使用 Python3,我該如何轉換
a =[[1,2],[0,1],[],[2,2],[],[2,13],[1,4],[6,1],[],[2,7]]
(關於它的空元素),到
b=[[[1, 2], [0, 1]], [[2, 2]], [[2, 13], [1, 4], [6, 1]], [[2, 7]]]
我很感激這方面的任何幫助。
謝謝
請嘗試以下腳本:
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)
使用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)
第一:
[[[1, 2], [0, 1]], [[2, 2]], [[2, 13], [1, 4], [6, 1]], [[2, 7]]]
你可以這樣做
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
或類似地,
def func(a):
b, c = [], []
c = [b[-1].append(i) for i in ([[]] + a ) if (i or b.append([]))]
return b
兩者都遵循基本相同的過程,
第二個片段浪費了一個額外的變量
你可以試試這個。
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)
輸出:
[[[1, 2], [0, 1]], [[2, 2]], [[2, 13], [1, 4], [6, 1]], [[2, 7]]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.