簡體   English   中英

帶有功能調用(很多括號)的python 3中的可讀代碼

[英]Readable code in python 3 with function calls (lots of parens)

我以前喜歡Python的可讀性,但是在轉到Pythion 3之后,似乎已經消失了。

思考一下:

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

可能不是問題出在Python 3上,而是我的編碼風格,但有。

看看所有的人!

現在,顯然我可以將其拆分為幾個局部變量,但是那很長。

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代替list comprehension來使代碼更具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)

可讀性可能不高,但是它消除了所有括號。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM