Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split List By Value and Keep Separators

Tags:

python

I have a list called list_of_strings that looks like this:

['a', 'b', 'c', 'a', 'd', 'c', 'e']

I want to split this list by a value (in this case c). I also want to keep c in the resulting split.

So the expected result is:

[['a', 'b', 'c'], ['a', 'd', 'c'], ['e']]]

Any easy way to do this?

like image 329
ScientiaEtVeritas Avatar asked Jul 19 '17 11:07

ScientiaEtVeritas


People also ask

Can Split have multiple separators?

Use the String. split() method to split a string with multiple separators, e.g. str. split(/[-_]+/) . The split method can be passed a regular expression containing multiple characters to split the string with multiple separators.

How do you split multiple values in a list in Python?

The split() method of the string class is fairly straightforward. It splits the string, given a delimiter, and returns a list consisting of the elements split out from the string. By default, the delimiter is set to a whitespace - so if you omit the delimiter argument, your string will be split on each whitespace.

How do you split a list into evenly sized chunks?

The easiest way to split list into equal sized chunks is to use a slice operator successively and shifting initial and final position by a fixed number.


1 Answers

You can use more_itertoools to accomplish this simply and clearly:

from more_itertools import split_after


lst = ["a", "b", "c", "a", "d", "c", "e"]
list(split_after(lst, lambda x: x == "c"))
# [['a', 'b', 'c'], ['a', 'd', 'c'], ['e']]

Another example, here we split words by simply changing the predicate:

lst = ["ant", "bat", "cat", "asp", "dog", "carp", "eel"]
list(split_after(lst, lambda x: x.startswith("c")))
# [['ant', 'bat', 'cat'], ['asp', 'dog', 'carp'], ['eel']]
like image 94
pylang Avatar answered Oct 12 '22 11:10

pylang