如何在Python中打断很长的代码行?

时间:2019-09-18 00:04:54

标签: python arrays

如何通过缩短每一行来使我的python代码更漂亮?例如:我有一个很长的if语句,我想使其更短=>将其长度分成几行:

if (imgA.shape[0] != imgB.shape[0]) and (imgA.shape[1] != imgB.shape[1]) and (imgA.shape[2] != imgB.shape[2]):

我想要这样的东西:

    if (imgA.shape[0] != imgB.shape[0]) and 
      (imgA.shape[1] != imgB.shape[1]) and
      (imgA.shape[2] != imgB.shape[2]):

但是出现语法错误。有人吗?

5 个答案:

答案 0 :(得分:2)

只比较数组本身吗?

if imgA.shape != imgB.shape:

或者其他元素很重要:

if imgA.shape[0:2] != imgB.shape[0:2]:

答案 1 :(得分:2)

您可以将其放在方括号中:

if ((imgA.shape[0] != imgB.shape[0]) and 
    (imgA.shape[1] != imgB.shape[1]) and 
    (imgA.shape[2] != imgB.shape[2])):
    #do stuff

答案 2 :(得分:1)

您可以使用\将同一条语句分成多行:

if (imgA.shape[0] != imgB.shape[0]) and \
    (imgA.shape[1] != imgB.shape[1]) and \
        (imgA.shape[2] != imgB.shape[2]):

答案 3 :(得分:1)

if (
    (imgA.shape[0] != imgB.shape[0]) and 
    (imgA.shape[1] != imgB.shape[1]) and
    (imgA.shape[2] != imgB.shape[2])
):
    #do something

我通常依靠引号中的括号来换行。这将在Jupyter笔记本中传递语法。

答案 4 :(得分:1)

不是确切的答案,但是一个好主意是为每个变量分配变量名:

check_shape_0 = imgA.shape[0] != imgB.shape[0]
check_shape_1 = imgA.shape[1] != imgB.shape[1]
check_shape_2 = imgA.shape[2] != imgB.shape[2]

if (check_shape_0) and (check_shape_1) and (check_shape_2):
    #Do something

对于将来的代码阅读器,重命名的布尔值将使您更清楚if语句中发生的事情。

如果布尔变量的变量名被精心挑选,则如果语句可以像英语一样被读取,这使得代码阅读起来非常舒适。

较短的名称使if语句更小。