簡體   English   中英

分割這條線的最pythonic方法?

[英]Most pythonic way to split this line?

我正在嘗試使用0到5的新值來重新分類具有0到15的值的數組。

我的條件如下:

con1 = np.in1d(arr, [0, 11, 13, 15]).reshape((y, x))  # new val 0
con2 = np.in1d(arr, [1, 2, 3, 4, 5]).reshape((y, x))  # new val 1
con3 = (arr == 6) | (arr == 7)                        # new val 2
con4 = (arr == 8) | (arr == 9)                        # new val 3
con5 = (arr == 10)                                    # new val 4
con6 = (arr == 12) | (arr == 14)                      # new val 5

我在python中有以下一行

return np.where(con1, 0, np.where(con2, 1, np.where(con3, 2, np.where(con4, 3, np.where(con5, 4, np.where(con6, 5, arr))))))

長度為128個字符(包括函數內的縮進)。 PEP8建議行不應超過79個字符。 但是我不確定在保持可讀性的同時將這行拆分為多行的最佳方法是什么。

我嘗試了兩種選擇,但它們似乎很難閱讀。

選項1:

return np.where(con1, 0, np.where(
    con2, 1, np.where(
        con3, 2, np.where(
            con4, 3, np.where(
                con5, 4, np.where(
                    con6, 5, arr))))))

選項2:

return np.where(con1, 0, 
                np.where(con2, 1, 
                         np.where(con3, 2, 
                                  np.where(con4, 3, 
                                           np.where(con5, 4, 
                                                    np.where(con6, 5, arr)
                                                    )))))

您可以單獨完成所有操作。 由於您可以逐步進行操作,因此更具可讀性。

filtered_result = np.where(con6, 5, arr)
filtered_result = np.where(con5, 4, filtered_result)
filtered_result = np.where(con4, 3, filtered_result)
filtered_result = np.where(con3, 2, filtered_result)
filtered_result = np.where(con2, 1, filtered_result)
filtered_result = np.where(con1, 0, filtered_result)

return filtered_result

要堅持使用pep8,這就是您要的方法,那么這就是要走的路

編輯

for循環也將大大減少重復性,並且仍然可讀。

connections = iter((con6, con5, con4, con3, co2, con1, con0))
filters = range(len(connections)-2, 0 -1)

filtered_result = np.where(next(connections), next(filters), arr)

for n, con, in zip(filters, connections):
    filtered_result = np.where(con, n, filtered_result)

return filtered_result

可能不太可讀,但您可以嘗試reduce

from functools import reduce

def some_func():

    ... some code maybe ...

    args = [con1, con2, con3, con4, con5, con6]
    return reduce(
            lambda prev_arg, new_arg: np.where(*new_arg, prev_arg), 
            enumerate(args[:-1]), 
            np.where(args[-1], len(args)-1, arr)
        )

暫無
暫無

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

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