我有一個清單如下,
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']]
我嘗試了以下方法,但也想保留帶有“法國”的句子。
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,"))))
uj5u.com熱心網友回復:
我想出了一個帶有嵌套回圈的解決方案,因為我對串列理解和 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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/427041.html
