Python 如何从展开列表创建嵌套列表?
我编写了一个函数来创建嵌套列表 例如:Python 如何从展开列表创建嵌套列表?,python,python-3.x,Python,Python 3.x,我编写了一个函数来创建嵌套列表 例如: input= ['a','b','c','','d','e','f','g','','d','s','d','a',''] 我想在'' 作为回报,我需要一个嵌套列表,如: [['a','b','c'],['d','e','f','g'],['d','s','d','a']] 尝试以下实现 >>> def foo(inlist, delim = ''): start = 0 try: while True
input= ['a','b','c','','d','e','f','g','','d','s','d','a','']
我想在''
作为回报,我需要一个嵌套列表,如:
[['a','b','c'],['d','e','f','g'],['d','s','d','a']]
尝试以下实现
>>> def foo(inlist, delim = ''):
start = 0
try:
while True:
stop = inlist.index(delim, start)
yield inlist[start:stop]
start = stop + 1
except ValueError:
# if '' may not be the end delimiter
if start < len(inlist):
yield inlist[start:]
return
>>> list(foo(inlist))
[['a', 'b', 'c'], ['d', 'e', 'f', 'g'], ['d', 's', 'd', 'a']]
编辑以在末尾添加空列表检查我将使用:
给予
欢迎来到堆栈溢出!我们鼓励你这样做。如果您有,请将其添加到问题中-如果没有,请先研究并尝试您的问题,然后再返回。仅当输入以
'
结尾时,才会返回正确的列表。例如['a',''b']
返回['a']]
而不是['a'],['b']]
@Tim:根据问题陈述我想在'
之前创建一个子列表,但它在shell中返回['a','b','c'],['d','f','g'],['d','d','a'],[]在返回之前
>>> from itertools import ifilter, groupby
>>> list(ifilter(lambda e: '' not in e,
(list(v) for k,v in groupby(inlist, key = lambda e:e == ''))))
[['a', 'b', 'c'], ['d', 'e', 'f', 'g'], ['d', 's', 'd', 'a']]
def nester(nput):
out = [[]]
for n in nput:
if n == '':
out.append([])
else:
out[-1].append(n)
if out[-1] == []:
out = out[:-1]
return out
l = ['a','b','c','','d','e','f','g','','d','s','d','a','']
from itertools import groupby
[list(g) for k, g in groupby(l, bool) if k]
[['a', 'b', 'c'], ['d', 'e', 'f', 'g'], ['d', 's', 'd', 'a']]