Python 海象運算子 :=


建立時間: 2023年1月17日 04:29
更新時間: 2023年1月17日 09:46

說明

:= 是 Python 3.8 新增的語法,稱為 “walrus operator”。這個運算子允許你在同一行內對變數賦值並檢查變數的值。

本篇將提供幾個範例,讓大家了解該如何使用

範例

範例1

輸出 words 字母長度在 length_limit 以下的字串

words = ['a', 'ab', 'abc', 'abcd', 'abcde', 'abcdef']
length_limit = 4

for word in words:
    word_length = len(word)

    if (word_length < length_limit):
        print(f'{word} 有 {word_length} 個字母')

輸出

a 有 1 個字母
ab 有 2 個字母
abc 有 3 個字母

上面這段程式碼使用 :=

words = ['a', 'ab', 'abc', 'abcd', 'abcde', 'abcdef']
length_limit = 4

for word in words:
    if ((word_length := len(word)) < length_limit):
        print(f'{word} 有 {word_length} 個字母')

雖然程式更簡潔了,但我感覺可讀性沒有比較好。

範例2

輸出 words 內的非空字串

words = ['', 'a', 'ab', 'abc', 'abcd', 'abcde', 'abcdef']
length_limit = 4

for word in words:
    if (word_length := len(word)):
        print(f'{word} 有 {word_length} 個字母')

使用 if 0 會是 False 的條件下搭配 := 根本就是絕配,雖然使用隱含的條件可讀性會降低,但這樣寫卻讓我感覺很簡潔有力

範例3

讀取檔案

with open('data.txt', 'r', encoding="UTF-8") as file:
    while line := file.readline():
        print(line, end='')

這個寫法也是讓我感覺簡潔有力

觀看次數: 3228
operatorpythonwalrus海象運算子:=
按讚追蹤 Enjoy 軟體 Facebook 粉絲專頁
每週分享資訊技術

一杯咖啡的力量,勝過千言萬語的感謝。

支持我一杯咖啡,讓我繼續創作優質內容,與您分享更多知識與樂趣!