ネストされたリストを作成する関数を作成しました。
例えば:
input= ['a','b','c','','d','e','f','g','','d','s','d','a','']
事前にサブリストを作成したい''
戻り値として、次のようなネストされたリストが必要です。
[['a','b','c'],['d','e','f','g'],['d','s','d','a']]
ネストされたリストを作成する関数を作成しました。
例えば:
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']]
別の可能な実装は、itertools.groupbyによるものです。ただし、結果をフィルタリングして [''] を削除する必要があります。しかし、ワンライナーに見えるかもしれませんが、上記の実装は直感的で読みやすいため、より Pythonic です。
>>> 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']]
私は使用しますitertools.groupby
:
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']]
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
最後に空のリストのチェックを追加するように編集