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

标签 python python-2.7 pep8

这是需要缩短的行。

tree_top = os.path.abspath(os.path.expanduser(os.path.expandvars(sys.argv[1])))
  • 我应该为每个过程创建一个变量吗?
  • 我是否应该为 os.path,abspathos.path.expandvarsos.path.expanduser 设置别名以使用更短的名称?
  • 我应该使用反斜杠吗?

最佳答案

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

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 - 我应该如何缩短这行 Python 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33723612/

相关文章:

python - 在函数 : Wrong handling indentation/bad-continuation. 中使用列表作为参数的 Pylint 错误无法找出原因

python - 缺少子进程命令的输出

python - 在数据帧行之间进行比较以进行删除

python - Pygame 的图像捕获实际上是如何工作的?

python - 根据美丽汤中 child 的文本值查找标签列表

python joblib.Parallel 与 Parallel-Python : parallelise over multiple cores of a single CPU?

python - Django Admin 同时使用 Django Reversion 和 Django-Import-Export

python - Pandas GroupBy 的绘图结果

python - 无法将 pyODBC 与 SQL Server 2008 Express R2 连接

python - flake8 和 "old style class declaration"