У меня есть следующие списки 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']]
Я написал следующий код для решения этих сценариев ios:
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