python 3中的可读代码,带有函数调用(很多parens)

Mig*_*ork 1 python syntax coding-style

我曾经喜欢Python的可读性,但在转移到Pythion 3后,这似乎已经消失了.

考虑一下:

print([k for k in hist_full_g(img.scale(12,44))])
Run Code Online (Sandbox Code Playgroud)

也许它不是Python 3的问题,而是我的编码风格,但是没有.

看看所有的parens!

现在很明显我可以将它分成几个局部变量,但这样做会很宽松.

img_scaled = img.scale(12,44)
histogram = hist_full_g()
histogram_array = [k for k in ]
print(histogram_array)
Run Code Online (Sandbox Code Playgroud)

我还可以在parens周围添加空间 - 实际上我有时会这样做,但它有点难看,而且我已经读过它的不良做法.

print( [ k for k in hist_full_g( img.scale(12, 44) ) ] )
Run Code Online (Sandbox Code Playgroud)

我该如何写它是可读的和"质量好"?

我不是在谈论这个例子,我的意思是一般.我的Python通常看起来像Lisp,我不认为它应该.

iCo*_*dez 5

您可以通过简单的调用替换列表理解来使您的代码更加pythonic list:

print(list(hist_full_g(img.scale(12,44))))
Run Code Online (Sandbox Code Playgroud)

从来没有一个很好的理由:

[x for x in iterable]
Run Code Online (Sandbox Code Playgroud)

因为list(iterable)产生相同的结果.

您可能还想使用两行来分解代码:

hist = hist_full_g(img.scale(12, 44))
print(list(hist))
# or
hist = list(hist_full_g(img.scale(12, 44)))
print(hist)
Run Code Online (Sandbox Code Playgroud)

你也会注意到我,在通话中添加了一个空格img.scale.使空格分隔函数参数可以使一切看起来不那么紧凑.事实上,这种风格在PEP 0008(Python代码的官方风格指南)中使用.


编辑:

也许你想使用for循环:

value = img.scale(12, 44)
for f in hist_full_g, list, print:
    value = f(value)
Run Code Online (Sandbox Code Playgroud)

可读性可能不是很好,但它摆脱了所有的括号.