我有以下列表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
原因如下:
通过执行
num_arr[:-1]
,您正在考虑使用丢弃的最后一个元素的num_arr,因此当"req"
是最后一个元素时,这种行为。将上述行替换为:它将作为您提供的所有测试用例的例外情况工作
作为旁注,如果允许您使用除
numpy
之外的外部python库,您可以利用more_itertools.split_before来完成该任务如果第一行始终为
"req"
。这是一行:结果:
这里有一个比纯python更快的解决方案
相关问题 更多 >
编程相关推荐