簡體   English   中英

根據條件將列表分解為列表列表

[英]Break list into list of lists based on condition

我有以下列表 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

原因在這一行:

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來完成該任務。

這是更快的純 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']]

如果第一個總是"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']]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM