【问题标题】:How to break very long code lines in Python? [duplicate]如何在 Python 中打破很长的代码行? [复制]
【发布时间】:2020-01-18 20:33:45
【问题描述】:

如何通过缩短每一行来使我的 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]):

但是我得到一个语法错误。有人吗?

【问题讨论】:

    标签: python arrays


    【解决方案1】:

    只比较数组本身?

    if imgA.shape != imgB.shape:
    

    或者如果其余元素很重要:

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

    【讨论】:

    • 好的,显然是个坏例子。但是,您如何将其拆分为多行?
    【解决方案2】:

    你可以把它放在括号里:

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

    【讨论】:

    • 这行得通。谢谢!
    【解决方案3】:
    if (
        (imgA.shape[0] != imgB.shape[0]) and 
        (imgA.shape[1] != imgB.shape[1]) and
        (imgA.shape[2] != imgB.shape[2])
    ):
        #do something
    

    我通常依靠括号括起参数来换行。这会在 Jupyter 笔记本中传递语法。

    【讨论】:

    • 虽然我不喜欢使用中间的缩进,而且我觉得代码越分段越容易理解,@Derek_Eden 的答案可能更正确。
    【解决方案4】:

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

    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 语句几乎可以像英语一样阅读,这使得代码阅读起来非常舒适。

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

    【讨论】:

      【解决方案5】:

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

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

      【讨论】:

      • 这很好。谢谢!
      • 乐于助人。 :)
      猜你喜欢
      • 2022-11-16
      • 2019-03-19
      • 1970-01-01
      • 2014-11-29
      • 2017-02-25
      • 2019-07-19
      • 1970-01-01
      • 2011-01-04
      • 2021-07-02
      相关资源
      最近更新 更多