我正在尝试用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)
)))))
你可以把它们分开做。这是更可读的,因为你可以遵循一步一步。你知道吗
坚持你的要求,这就是pep8,那么这就是你要走的路
编辑
for循环还可以显著减少重复性,并且仍然可读。你知道吗
可能不太可读,但您可以尝试
reduce
:相关问题 更多 >
编程相关推荐