Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
342 views
in Technique[技术] by (71.8m points)

python - Split a list into chunks determined by a separator

I have this list (python):

[[item1],[item2],[item3],[/],[item4],[item5],[item6],[/]...]

I want to separate these into chunks and the elements that will go into each chunk are the elements before the separator "/".

So my chunks would look like:

chunk1 = [[item1],[item2],[item3]]
chunk2 = [[item4],[item5],[item6]]

I've tried and tried, nothing efficient came to mind. Tried looping through it with a for and and if element[x] == '/' then get some positions. It's very dirty and doesn't properly work.

Any help would be appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The usual approach for collecting contiguous chunks is to use itertools.groupby, for example:

>>> from itertools import groupby
>>> blist = ['item1', 'item2', 'item3', '/', 'item4', 'item5', 'item6', '/']
>>> chunks = (list(g) for k,g in groupby(blist, key=lambda x: x != '/') if k)
>>> for chunk in chunks:
...     print(chunk)
...     
['item1', 'item2', 'item3']
['item4', 'item5', 'item6']

(Your representation of your list [item1],[item2],[item3],[/], makes it look like each of your elements in the list is actually a list, in which case the same approach will work, you simply need to compare against ['/'] or whatever your separator is.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...