python:split一个字符串列表在某个值之前变成多个列表

python:split a list of strings into multiple lists before a certain value

我有如下列表,

my_list = ['France, the weather is nice', 'the house is beautiful', 'we have a fresh start here','France, the dinner is amazing', 'the lady is lovely', 'France, the house is beautiful','the location is fascinating']

每当字符串中出现单词 'France,' 时,我想将列表拆分为多个列表,因此输出应该是,

desired_list = [['France, the weather is nice', 'the house is beautiful', 'we have a fresh start here'],['France, the dinner is amazing', 'the lady is lovely'],['France, the house is beautiful','the location is fascinating']]

我试过下面的,但也想保留有'France,'的句子。

new_list =[list(y) for x, y in itertools.groupby(my_list, lambda z: z.startswith('France,)) if not x]

另一个答案

除了Titouan L给出的答案,我还用more_itertools

找到了答案
import more_itertools as miter
print(list(miter.split_before(my_list, lambda x: x.startswith("France,"))))

我想出了一个嵌套循环的解决方案,因为我对列表理解和 lambda 表达式不是很有经验。

my_list = ['France, the weather is nice', 'the house is beautiful', 'we have a fresh start here', 'France, the dinner is amazing',
           'the lady is lovely', 'France, the house is beautiful', 'the location is fascinating']

new_list = []
sub_list = []
for i in my_list:
    if i.startswith('France,'):
        if sub_list != []:
            new_list.append(sub_list)
            sub_list=[]

    sub_list.append(i)
new_list.append(sub_list)

纯属娱乐,使用递归:

my_list = ['France, the weather is nice', 'the house is beautiful', 'we have a fresh start here', 'France, the dinner is amazing', 'the lady is lovely', 'France, the house is beautiful','the location is fascinating']


def split_list(index=len(my_list) - 1):
    if index < 0:
        return []
    if not my_list[index].startswith('France,'):
        data = split_list(index - 1)
        data[-1].append(my_list[index])
        return data
    else:
        return split_list(index - 1) + [[my_list[index]]]


print(split_list())

输出:

[['France, the weather is nice', 'the house is beautiful', 'we have a fresh start here'], ['France, the dinner is amazing', 'the lady is lovely'], ['France, the house is beautiful', 'the location is fascinating', 'the location is fascinating']]

绝对不是最有效的:)