幾個技巧讓你的Python程式碼更專業
最近幾年時間,國內的Python開發者越來越多,但是很多開發者都是從其他程式語言轉換陣營來到Python的。正是因為這樣的原因,很多Python開發者的程式碼中都保留了其他語言的程式設計習慣,這樣的程式碼看起來就顯得很不專業,非常的不”Pythonic“。
其實Python語言有很多專屬的“程式設計慣例”,”慣例“這個詞按照詞典上的解釋就是“習慣的做法,常規的辦法,一貫的做法”。作為一個Python開發者,尤其是”跨界程式設計師“,如果能夠掌握這些慣例,就可以寫出“Pythonic”的程式碼。簡單的說就是:只需幾個小技巧,就能讓你的Python程式碼看起來特別專業。
點選加入千人大群交流學習,全套課程影片-原始碼-軟體安裝包免費贈送~
技巧1
:讓程式碼既可以被匯入又可以被執行。
if
__name__
==
‘__main__’
:
技巧2
:用下面的方式判斷邏輯“真”或“假”。
if
x
:
if
not
x
:
“Pythonic”的程式碼:
name
=
‘jackfrued’
fruits
=
[
‘apple’
,
‘orange’
,
‘grape’
]
owners
=
{
‘1001’
:
‘駱昊’
,
‘1002’
:
‘王大錘’
}
if
name
and
fruits
and
owners
:
(
‘I love fruits!’
)
“跨界程式設計師”的程式碼:
name
=
‘jackfrued’
fruits
=
[
‘apple’
,
‘orange’
,
‘grape’
]
owners
=
{
‘1001’
:
‘駱昊’
,
‘1002’
:
‘王大錘’
}
if
name
!=
‘’
and
len
(
fruits
)
>
0
and
owners
!=
{}:
(
‘I love fruits!’
)
技巧3
:善於使用in運算子。
if
x
in
items
:
for
x
in
items
:
“Pythonic”的程式碼:
name
=
‘Hao LUO’
if
‘L’
in
name
:
(
‘The name has an L in it。’
)
“跨界程式設計師”的程式碼:
name
=
‘Hao LUO’
if
name
。
find
(
‘L’
)
!=
-
1
:
(
‘This name has an L in it!’
)
技巧4
:不使用臨時變數交換兩個值。
a
,
b
=
b
,
a
技巧5
:用序列構建字串。
“Pythonic”的程式碼:
chars
=
[
‘j’
,
‘a’
,
‘c’
,
‘k’
,
‘f’
,
‘r’
,
‘u’
,
‘e’
,
‘d’
]
name
=
‘’
。
join
(
chars
)
(
name
)
“跨界程式設計師”的程式碼:
chars
=
[
‘j’
,
‘a’
,
‘c’
,
‘k’
,
‘f’
,
‘r’
,
‘u’
,
‘e’
,
‘d’
]
name
=
‘’
for
char
in
chars
:
name
+=
char
(
name
)
技巧6
:EAFP(
E
asier to
A
sk
F
orgiveness than
P
ermission)優於LBYL(
L
ook
B
efore
Y
ou
L
eap)。
“Pythonic”的程式碼:
d
=
{
‘x’
:
‘5’
}
try
:
value
=
int
(
d
[
‘x’
])
(
value
)
except
(
KeyError
,
TypeError
,
ValueError
):
value
=
None
“跨界程式設計師”的程式碼:
d
=
{
‘x’
:
‘5’
}
if
‘x’
in
d
and
isinstance
(
d
[
‘x’
],
str
)
and
d
[
‘x’
]
。
isdigit
():
value
=
int
(
d
[
‘x’
])
(
value
)
else
:
value
=
None
技巧7
:使用enumerate進行迭代。
“Pythonic”的程式碼:
fruits
=
[
‘orange’
,
‘grape’
,
‘pitaya’
,
‘blueberry’
]
for
index
,
fruit
in
enumerate
(
fruits
):
(
index
,
‘:’
,
fruit
)
“跨界程式設計師”的程式碼:
fruits
=
[
‘orange’
,
‘grape’
,
‘pitaya’
,
‘blueberry’
]
index
=
0
for
fruit
in
fruits
:
(
index
,
‘:’
,
fruit
)
index
+=
1
技巧8
:用生成式生成列表、集合和字典。
“Pythonic”的程式碼:
data
=
[
7
,
20
,
3
,
15
,
11
]
result
=
[
num
*
3
for
num
in
data
if
num
>
10
]
(
result
)
“跨界程式設計師”的程式碼:
data
=
[
7
,
20
,
3
,
15
,
11
]
result
=
[]
for
i
in
data
:
if
i
>
10
:
result
。
append
(
i
*
3
)
(
result
)
技巧9
:用zip組合鍵和值來建立字典。
“Pythonic”的程式碼:
keys
=
[
‘1001’
,
‘1002’
,
‘1003’
]
values
=
[
‘駱昊’
,
‘王大錘’
,
‘白元芳’
]
d
=
dict
(
zip
(
keys
,
values
))
(
d
)
“跨界程式設計師”的程式碼:
keys
=
[
‘1001’
,
‘1002’
,
‘1003’
]
values
=
[
‘駱昊’
,
‘王大錘’
,
‘白元芳’
]
d
=
{}
for
i
,
key
in
enumerate
(
keys
):
d
[
key
]
=
values
[
i
]
(
d
)
講到這裡,大家可以把自己的程式碼對號入座一下,看看自己寫的是“Pythonic”的還是“跨界程式設計師”程式碼。如果想讓自己的程式碼更加專業,一定要先從寫出“Pythonic”的程式碼開始。後面我還會繼續為大家分享編寫Python程式碼的技巧,掌握這些技巧肯定能讓你的Python程式碼帥到沒朋友的。
點選加入千人大群交流學習,全套課程影片-原始碼-軟體安裝包免費贈送~