2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonの便利な小ネタ集 ~実践試験で得た知見まとめ~

Posted at

先日、Python3 エンジニア認定実践試験に合格 しました!
試験勉強を通して、個人的に「これは覚えておくと便利!」と感じた小技やモジュールたちを、備忘録がてら簡潔にまとめて紹介します。

① f文字列の変数表示

Python 3.8から、f文字列で変数名と値を一緒に出力できるようになりました。デバッグやログ出力の際に役立ちそうです。

ans = 42

# いままでやっていたデバッグ出力
print(f'ans={ans}') # 出力: ans=42

# 以下のようにした方が、変数名を1つ書くだけで済む
print(f'{ans=}') # 出力: ans=42

② 要素の集計

複数の値が登場するリストなどから、「各要素が何回登場したか」を一瞬で集計できます。

from collections import Counter

fruits = ['apple', 'banana', 'apple', 'orange', 'banana']
count = Counter(fruits)
print(count)
# 出力: Counter({'apple': 2, 'banana': 2, 'orange': 1})

③ 関数実行のパフォーマンス比較

関数の処理速度をミリ秒単位で精密に測れます。関数の最適化や比較検証に便利だと思いました。

import timeit

def test():
    return sum(x for x in range(1000))

print(timeit.timeit(test, number=100)) # 関数testを100回実行したときの合計時間(秒単位)を測定。
# 出力: 0.01234

④ セキュアなランダム文字列を生成

randomよりも暗号論的に安全な乱数生成ができるsecretsを使えば、実用的なパスワードも安心して作れます。

import secrets
import string

alphabet = string.ascii_letters + string.digits
password = ''.join(secrets.choice(alphabet) for _ in range(12))
print(password)
# 出力: a9ZkX2mLq7Ty

⑤ リスト結合で長さの違いを吸収

zip:最短の要素数に合わせてペアを作る

a = [1, 2, 3]
b = ['A', 'B']
print(list(zip(a, b)))
# 出力: [(1, 'A'), (2, 'B')]

zip_longest:最長のリストに合わせる(不足分をfillvalueで補完)

from itertools import zip_longest

print(list(zip_longest(a, b, fillvalue='-')))
# 出力: [(1, 'A'), (2, 'B'), (3, '-')]

⑥ オブジェクトコピーで浅い・深いを使い分け

copy.copy():浅いコピー(オブジェクトの第一層だけコピーする)

import copy

a = [1, 2, [3, 4]]
b = copy.copy(a)
b[0] = 10 # bの第一層は独立しているので影響なし
b[2][0] = 30 # b[2]は参照を共有しているのでa[2][0]も変わる

print(a) # [1, 2, [30, 4]]
print(b) # [10, 2, [30, 4]]

copy.deepcopy():深いコピー(オブジェクトの中身すべてを再帰的にコピーする)

import copy

a = [1, 2, [3, 4]]
b = copy.deepcopy(a)
b[2][0] = 30 # bの内部要素は独立しているのでaには影響なし

print(a) # [1, 2, [3, 4]]
print(b) # [1, 2, [30, 4]]

最後に

試験勉強をする中で、便利な技を知ることができたので良かったです。
この記事が、みなさんの開発のちょっとした手助けになれば幸いです!
他にも、覚えておくと便利な技がありましたら、コメントで教えていただけると嬉しいです🙇

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?