【问题标题】:Python: split a list into multiple lists based on a specific elementPython:根据特定元素将列表拆分为多个列表
【发布时间】:2021-08-10 14:21:24
【问题描述】:

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

    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 不能预先声明。由于数组中的元素数量可能会有所不同。所以我需要根据要求找到一种动态声明列表的方式。

【问题讨论】:

标签: python python-3.x list append


【解决方案1】:

您可以使用列表的列表来存储这些。因此,如果值为 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']]

【讨论】:

    【解决方案2】:

    您可以执行以下操作:

    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)
    

    【讨论】:

    • 这不符合 OP 的要求:新列表是动态创建的,因为原始列表的长度是任意的。它还忽略了从结果中删除“步骤”的澄清注释。
    【解决方案3】:

    试试这个

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

    【讨论】:

    • 这不符合 OP 的要求:新列表是动态创建的,因为原始列表的长度是任意的。它还忽略了从结果中删除“步骤”的澄清注释。
    【解决方案4】:

    虽然内存效率不如 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)]
    

    返回:

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

    【讨论】:

      猜你喜欢
      • 2022-01-04
      • 2019-03-06
      • 2018-12-22
      • 1970-01-01
      • 2020-10-07
      • 2015-12-14
      • 2022-12-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多