より良い Python コードを書く
15294 ワード
序章
この記事には、より慣用的な Python コードを作成するために私が過去数か月にわたって学んだ、Python コーディングのプラクティスがまとめられています.
1. 複数課題
異なる変数に対して同じ値を初期化します.
# Instead of this
x = 10
y = 10
z = 10
# Use this
x = y = z = 10
2. 変数のアンパック
x, y = [1, 2]
# x = 1, y = 2
x, *y = [1, 2, 3, 4, 5]
# x = 1, y = [2, 3, 4, 5]
x, *y, z = [1, 2, 3, 4, 5]
# x = 1, y = [2, 3, 4], z = 5
3. 変数の交換
# Instead of this
temp = x
x = y
y = temp
# Use this
x, y = y, x
4. ネームケース
Python では、変数と関数の名前には
snake_case
よりも camelCase
が優先されます.# Instead of this
def isEven(num):
pass
# Use this
def is_even(num):
pass
5. 条件式
if-else ステートメントを 1 行に結合できます.
# Instead of this
def is_even(num):
if num % 2 == 0:
print("Even")
else:
print("Odd")
# Use this
def is_even(num):
print("Even") if num % 2 == 0 else print("Odd")
# Or this
def is_even(num):
print("Even" if num % 2 == 0 else "Odd")
6. 文字列のフォーマット
name = "Dobby"
item = "Socks"
# Instead of this
print("%s likes %s." %(name, item))
# Or this
print("{} likes {}.".format(name, item))
# Use this
print(f"{name} likes {item}.")
f-strings は Python 3.6 で導入され、他の文字列フォーマット方法よりも高速で読みやすくなっています.
7. 比較演算子
# Instead of this
if 99 < x and x < 1000:
print("x is a 3 digit number")
# Use this
if 99 < x < 1000:
print("x is a 3 digit number")
8. リストまたはタプルの繰り返し
リスト要素にアクセスするためにインデックスを使用する必要はありません.代わりに、これを行うことができます.
numbers = [1, 2, 3, 4, 5, 6]
# Instead of this
for i in range(len(numbers)):
print(numbers[i])
# Use this
for number in numbers:
print(number)
# Both of these yields the same output
9. enumerate() の使用
インデックスと値の両方が必要な場合は、
enumerate()
を使用できます.names = ['Harry', 'Ron', 'Hermione', 'Ginny', 'Neville']
for index, value in enumerate(names):
print(index, value)
10. 検索に Set を使用する
セット内の検索は、リスト (O(n)) に比べて高速です (O(1)).
# Instead of this
l = ['a', 'e', 'i', 'o', 'u']
def is_vowel(char):
if char in l:
print("Vowel")
# Use this
s = {'a', 'e', 'i', 'o', 'u'}
def is_vowel(char):
if char in s:
print("Vowel")
11. リスト内包表記
リストの要素が偶数の場合、それらを 2 に乗算する次のプログラムを検討してください.
arr = [1, 2, 3, 4, 5, 6]
res = []
# Instead of this
for num in arr:
if num % 2 == 0:
res.append(num * 2)
else:
res.append(num)
# Use this
res = [(num * 2 if num % 2 == 0 else num) for num in arr]
12. 反復辞書
dict.items()
を使用して辞書を反復処理します.roll_name = {
315: "Dharan",
705: "Priya",
403: "Aghil"
}
# Instead of this
for key in roll_name:
print(key, roll_name[key])
# Do this
for key, value in roll_name.items():
print(key, value)
ソース
Reference
この問題について(より良い Python コードを書く), 我々は、より多くの情報をここで見つけました https://dev.to/dharaneeswaranr/write-better-python-code-51j0テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol