2024年9月14日 星期六

Python 之禪,import this是有趣的彩蛋

 

在Python IDLE的交談視窗中,可以輸入import this,您將獲得一顆有趣的彩蛋。我們試著用ChatGPT把下面文字,翻譯成中文。
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

使用ChatGPT英譯中,獲得下列文章。

Python之禪,作者:Tim Peters

美麗勝於醜陋。
明確勝於隱晦。
簡單勝於複雜。
複雜勝於繁瑣。
平坦勝於嵌套。
稀疏勝於密集。
可讀性很重要。
特例不足以打破規則。
雖然實用性勝於純粹性。
錯誤絕不應該默默無聲地通過。
除非明確地靜音。
面對模糊性,拒絕猜測的誘惑。
應該有一種——最好只有一種——明顯的方法來做事。
雖然這種方法一開始可能不明顯,除非你是荷蘭人。
現在勝於永不。
雖然永不往往比立刻好。
如果實現很難解釋,那就是個壞主意。
如果實現容易解釋,可能是個好主意。
命名空間是一個非常棒的主意——讓我們多使用它們吧!

我們再用ChaptGPT幫我們舉例。

範例一、Beautiful is better than ugly. (美麗勝於醜陋)
代碼應該清晰、美觀,結構合理。例如,選擇具描述性的變量名勝過短而不明確的名稱:

1
2
3
4
5
# 醜陋
x = 100

# 美麗
number_of_apples = 100

範例二、Explicit is better than implicit. (明確勝於隱晦)
寫代碼時應該避免隱晦的行為,讓代碼的意圖清晰可見。例如,選擇顯式地轉換類型,而不是隱式的:

1
2
3
4
5
6
7
# 隱晦
x = "42"
y = x + 1  # 這會拋出錯誤

# 明確
x = "42"
y = int(x) + 1  # 顯式地轉換類型

範例三、Simple is better than complex. (簡單勝於複雜)
代碼應保持簡單,不應為了「炫技」而引入不必要的複雜性。例如,使用簡單的 for-loop 而不是嵌套和過度複雜的邏輯:

1
2
3
4
5
6
7
8
# 複雜
result = [x**2 for x in range(10) if x % 2 == 0]

# 簡單
result = []
for x in range(10):
    if x % 2 == 0:
        result.append(x**2)


範例四、Readability counts. (可讀性很重要)
代碼可讀性極為重要,這是維護性和協作開發中的關鍵。例如,適當地縮進、添加註釋讓代碼更具可讀性:

1
2
3
4
5
6
7
# 難以閱讀
def f(x):return x**2+1

# 易於閱讀
def square_plus_one(x):
    """返回數字 x 的平方加 1"""
    return x**2 + 1

範例五、Errors should never pass silently. (錯誤絕不應該默默無聲地通過)
當出現錯誤時,應該明確處理或顯示,而不是忽略。例如,使用 try...except 來捕捉並處理異常:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# 錯誤被靜默忽略
try:
    result = 1 / 0
except:
    pass  # 沒有任何反應

# 明確處理錯誤
try:
    result = 1 / 0
except ZeroDivisionError:
    print("不能除以零")

範例六、If the implementation is hard to explain, it's a bad idea. (如果實現很難解釋,那就是個壞主意)
如果代碼實現非常複雜且難以解釋,應考慮重新設計。代碼應該易於理解:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# 難以理解
def foo(lst):
    return {x:lst.count(x) for x in lst}

# 易於理解
def count_occurrences(lst):
    """計算列表中每個元素的出現次數"""
    occurrences = {}
    for item in lst:
        if item in occurrences:
            occurrences[item] += 1
        else:
            occurrences[item] = 1
    return occurrences

以上這些例子展示了 The Zen of Python 的核心理念,即保持代碼簡單、明確、可讀,並避免不必要的複雜性。

沒有留言:

張貼留言