I have a word list like below. I want to split the list by .
. Is there any better or useful code in Python 3?
a = ['this', 'is', 'a', 'cat', '.', 'hello', '.', 'she', 'is', 'nice', '.'] result = [] tmp = [] for elm in a: if elm is not '.': tmp.append(elm) else: result.append(tmp) tmp = [] print(result) # result: [['this', 'is', 'a', 'cat'], ['hello'], ['she', 'is', 'nice']]
Add test cases to handle it correctly.
a = ['this', 'is', 'a', 'cat', '.', 'hello', '.', 'she', 'is', 'nice', '.'] b = ['this', 'is', 'a', 'cat', '.', 'hello', '.', 'she', 'is', 'nice', '.', 'yes'] c = ['.', 'this', 'is', 'a', 'cat', '.', 'hello', '.', 'she', 'is', 'nice', '.', 'yes'] def split_list(list_data, split_word='.'): result = [] sub_data = [] for elm in list_data: if elm is not split_word: sub_data.append(elm) else: if len(sub_data) != 0: result.append(sub_data) sub_data = [] if len(sub_data) != 0: result.append(sub_data) return result print(split_list(a)) # [['this', 'is', 'a', 'cat'], ['hello'], ['she', 'is', 'nice']] print(split_list(b)) # [['this', 'is', 'a', 'cat'], ['hello'], ['she', 'is', 'nice'], ['yes']] print(split_list(c)) # [['this', 'is', 'a', 'cat'], ['hello'], ['she', 'is', 'nice'], ['yes']]
Python String split() MethodThe split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.
In Python, we can split a list into n sublists a number of different ways. Given a length, or lengths, of the sublists, we can use a loop, or list comprehension to split a list into n sublists. A more efficient way to split a list into sublists is with yield().
To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.
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.
Using itertools.groupby
from itertools import groupby a = ['this', 'is', 'a', 'cat', '.', 'hello', '.', 'she', 'is', 'nice', '.'] result = [list(g) for k,g in groupby(a,lambda x:x=='.') if not k] print (result) #[['this', 'is', 'a', 'cat'], ['hello'], ['she', 'is', 'nice']]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With