根据条件将列表拆分为列表列表

2024-05-23 18:50:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下列表x1、x2、x3,我想将其分块到下面提到的各个输出中:

x1 = ['req', 'a', 'b', 'c', 'req', 'd', 'e', 'req', 'f']

expected_out1 = [['req', 'a', 'b', 'c'], ['req', 'd', 'e'], ['req', 'f']]

x2 = ['req', 'a', 'b', 'c', 'req', 'd', 'e', 'req', 'f', 'req']

expected_out2 = [['req', 'a', 'b', 'c'], ['req', 'd', 'e'], ['req', 'f'], ['req']]

x3 = ['req', 'a', 'b', 'c', 'req', 'd', 'e', 'req', 'req']

expected_out3 = [['req', 'a', 'b', 'c'], ['req', 'd', 'e'], ['req'], ['req']]

我编写了以下代码来解决这些场景:

import numpy as np
def split_basedon_condition(b):
    num_arr = np.array(b)
    arrays = np.split(num_arr, np.where(num_arr[:-1] == "req")[0])
    return [i for i in [i.tolist() for i in arrays] if i != []]

但我得到了以下结果:

split_basedon_condition(x1)
actual_out1 = [['req', 'a', 'b', 'c'], ['req', 'd', 'e'], ['req', 'f']] # expected

split_basedon_condition(x2)
actual_out2 = [['req', 'a', 'b', 'c'], ['req', 'd', 'e'], ['req', 'f', 'req']] # not expected

split_basedon_condition(x3)
actual_out3 = [['req', 'a', 'b', 'c'], ['req', 'd', 'e'], ['req', 'req']] # not expected

Tags: npconditionreqnumsplitexpectedx1x2
3条回答

原因如下:

arrays = np.split(num_arr, np.where(num_arr[:-1] == "req")[0])

通过执行num_arr[:-1],您正在考虑使用丢弃的最后一个元素的num_arr,因此当"req"是最后一个元素时,这种行为。将上述行替换为:

arrays = np.split(num_arr, np.where(num_arr == "req")[0])

它将作为您提供的所有测试用例的例外情况工作

作为旁注,如果允许您使用除numpy之外的外部python库,您可以利用more_itertools.split_before来完成该任务

如果第一行始终为"req"。这是一行:

def func(l):
    return list(map(lambda x: x.insert(0, "req") or x, map(list, "".join(l[1:]).split("req"))))

结果:

[['req', 'a', 'b', 'c'], ['req', 'd', 'e'], ['req', 'f']]
[['req', 'a', 'b', 'c'], ['req', 'd', 'e'], ['req', 'f'], ['req']]
[['req', 'a', 'b', 'c'], ['req', 'd', 'e'], ['req'], ['req']]

这里有一个比纯python更快的解决方案

def split(arr, pred):
    j = len(arr)
    for i,_ in filter(lambda x: x[1] == pred, zip(range(j-1, -1, -1), reversed(arr))):
        yield arr[i:j]
        j = i

list(split(['req', 'a', 'b', 'c', 'req', 'd', 'e', 'req', 'req'], 'req'))
# [['req'], ['req'], ['req', 'd', 'e'], ['req', 'a', 'b', 'c']]

相关问题 更多 >