[英]How can I split a list into smaller lists?
I have a list: 我有一个清单:
lists = (['1','2','3','S','3','4','S','4','6','7'])
And I want to split the list into s smaller list everytime 'S' appears and eliminate 'S' into something like: 而且我想在每次出现“ S”时将列表拆分为较小的列表,并将“ S”消除为类似以下内容:
([['1','2','3'],['3','4],['4','6','7']])
My code: 我的代码:
def x (lists):
empty = ''
list = []
for x in lists:
if x == empty:
list[-1:].append(x)
else:
list.append([x])
return (list)
I tried something like this, but I am quite new to python, and Im getting nowhere. 我尝试过类似的方法,但是我对python还是很陌生,而我却一无所获。 Nothing fancy please, how would I fix what I have? 没什么好想的,我该如何修理我拥有的东西?
Try itertools.groupby()
: 试试itertools.groupby()
:
>>> from itertools import groupby
>>> lists = ['1','2','3','S','3','4','S','4','6','7']
>>> [list(g[1]) for g in groupby(lists, lambda i:i!='S') if g[0]]
[['1', '2', '3'], ['3', '4'], ['4', '6', '7']]
Maybe something like map(list,''.join(lists).split('S'))
也许像map(list,''.join(lists).split('S'))
Alternately, [list(s) for s in ''.join(lists).split('S'))
或者, [list(s) for s in ''.join(lists).split('S'))
Well, may be funny, but this should work: 好吧,也许很有趣,但这应该可以:
[s.split('#') for s in '#'.join(lists).split('#S#')]
Instead of the '#'
any character can be used if it's unlikely to appear in lists
. 如果不太可能出现在lists
则可以使用任何字符代替'#'
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.