繁体   English   中英

我应该如何缩短这行Python代码?

[英]How should I shorten this line of Python code?

这是需要缩短的行。

tree_top = os.path.abspath(os.path.expanduser(os.path.expandvars(sys.argv[1])))
  • 我应该为每个程序创建一个变量吗?
  • 我应该使用os.path,abspathos.path.expandvarsos.path.expanduseros.path,abspath名称吗?
  • 我应该使用反斜杠吗?

减小宽度的最简单方法是在括号内使用隐式线延续:

tree_top = os.path.abspath(
    os.path.expanduser(
        os.path.expandvars(sys.argv[1])
    )
)

或者,只需选择所需的os.path部分:

from os.path import abspath, expanduser, expandvars

tree_top = abspath(expanduser(expandvars(sys.argv[1])))

或者使用两者的某种组合。

您可以使用Python的一个名为Implicit Line Joining的功能

括号之间的代码隐含地是同一指令的一部分,因此,您可以通过将表达式分散在多行来“缩短”表达式:

tree_top = os.path.abspath(
    os.path.expanduser(
        os.path.expandvars(
            sys.argv[1]
        )
    )
)

现在,每行不超过80个字符,并且是干净的PEP8代码。

如果您的操作的每个步骤都更明确定义,使用中间变量也是缩短每个单独行的好方法。 在某些情况下,它可以帮助使代码更清晰,但这里的中间步骤不太有用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM