使用有或没有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)
<小时 />lst:
[[[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]]]