Python:根据特定元素将列表拆分为多个列表

Python: split a list into multiple lists based on a specific element

我想根据列表中的元素将以下列表拆分为子列表。

    array=['first','sentence','step','second','sentence']
    for i in array:
        if i!='step':
            newlist1.append(i)
        else:
            (stop appending in newlist1 and start appending in say newlist2)

newlist1 和 newlist2 不能预先声明。由于数组中的元素数量可能会有所不同。所以我需要找到一种动态的方式来根据要求声明列表。

您可以执行以下操作:

array=['first','sentence','step','second','sentence']
newlist1 = []
newlist2 = []
check = True
for i in array:
    if i!='step' and check:
        newlist1.append(i)
    else:
        check = False
        newlist2.append(i)

您可以使用列表的列表来存储这些。因此,如果值为 step 则开始一个新列表,如果不是则附加到最后一个列表。

from pprint import pprint

lists = [[]]
array = ['first', 'sentence', 'step', 'second', 'sentence', 'step', 'thrid', 'step', 'some', 'other', 'sentance']
for i in array:
    if i == 'step':
        lists.append([])
    else:
        lists[-1].append(i)
pprint(lists)

输出

[['first', 'sentence'],
 ['second', 'sentence'],
 ['thrid'],
 ['some', 'other', 'sentance']]

试试这个

index = array.index('step') 
if index and index < len(array):
    newlist1 = array[0:index+1]
    newlist2 = array[index+1:]

虽然记忆效率不如 Chris Doyle 的答案,但我更喜欢理解这样的东西,除非它们太冗长以至于无法放在一行中。

array = ['first', 'sentence', 'step', 'second', 'sentence', 'step', 'third', 'step', 'some', 'other', 'sentence']

def split_list(lst, sep):
    return [i.split() for i in ' '.join(lst).split(sep)]

print(split_list(array, 'step'))

结果

[['first', 'sentence'], ['second', 'sentence'], ['third'], ['some', 'other', 'sentence']]

奖金

如果最终目标是句子列表而不是列表列表,只需将第一个 .split() 替换为 .strip()

[i.strip() for i in ' '.join(lst).split(sep)]

Returns:

['first sentence', 'second sentence', 'third', 'some other sentence']