gpt4 book ai didi

python - 带有函数调用的 python 3 中的可读代码(很多括号)

转载 作者:太空宇宙 更新时间:2023-11-04 08:59:01 24 4
gpt4 key购买 nike

我以前喜欢 Python 的可读性,但在迁移到 Python 3 之后,这似乎消失了。

思考一下:

print([k for k in hist_full_g(img.scale(12,44))])

也许问题不在于 Python 3,而是我的编码风格,但 w/e。

看看所有的 parent !

现在显然我可以将它拆分成几个局部变量,但那会很麻烦。

img_scaled = img.scale(12,44)
histogram = hist_full_g()
histogram_array = [k for k in ]
print(histogram_array)

我还可以在括号周围添加空格 - 实际上我有时会这样做,但它有点丑陋,而且我已经读到这是不好的做法。

print( [ k for k in hist_full_g( img.scale(12, 44) ) ] )

我应该如何编写才可读且“质量好”?

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

最佳答案

您可以通过简单地调用 list 来替换列表理解,从而使您的代码更符合 Python 风格:

print(list(hist_full_g(img.scale(12,44))))

从来没有好的理由去做:

[x for x in iterable]

因为 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)

您还会注意到,我在调用 img.scale 时在 , 之后添加了一个空格。用空格分隔函数参数可以防止一切看起来那么紧凑。事实上,这种风格贯穿始终 PEP 0008 (Python 代码的官方风格指南)。


编辑:

也许您想使用 for 循环:

value = img.scale(12, 44)
for f in hist_full_g, list, print:
value = f(value)

可读性可能不是很好,但它去掉了所有括号。

关于python - 带有函数调用的 python 3 中的可读代码(很多括号),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27389790/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com