1
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で使える1行コード10選

Posted at

Pythonには、たった1行で実用的な処理を実現できる「ワンライナー」が数多く存在します。


1. 変数の入れ替え

a, b = 5, 10
a, b = b, a
print(a, b)  # 10 5

入れ替え用の一時変数が不要です。


2. 文字列を逆順にする

s = "Python"
print(s[::-1])  # nohtyP

スライス機能で一瞬で逆順にできます。


3. 回文チェック

s = "level"
print(s == s[::-1])  # True

文字列が前から読んでも後ろから読んでも同じかを判定します。


4. 階乗を計算

import math
n = 5
print(math.prod(range(1, n+1)))  # 120

math.prodを使えばループなしで階乗計算。


5. ネストされたリストを平坦化

lst = [[1, 2], [3, 4], [5]]
flat = [i for sub in lst for i in sub]
print(flat)  # [1, 2, 3, 4, 5]

二重ループを1行にまとめられます。


6. 偶数だけを抽出

even_numbers = [x for x in range(10) if x % 2 == 0]
print(even_numbers)  # [0, 2, 4, 6, 8]

条件付きリスト内包表記で簡単にフィルタリング。


7. 2つの辞書をマージ

d1 = {"a": 1, "b": 2}
d2 = {"c": 3, "d": 4}
merged = {**d1, **d2}
print(merged)  # {'a': 1, 'b': 2, 'c': 3, 'd': 4}

Python3.5以降ならこれで辞書結合可能。


8. 要素の出現回数を数える

from collections import Counter
lst = ["apple", "banana", "apple", "orange", "banana"]
print(Counter(lst))  # Counter({'apple': 2, 'banana': 2, 'orange': 1})

頻度分析に便利。


9. 重複を除去してユニーク要素取得

lst = [1, 2, 2, 3, 4, 4, 5]
print(set(lst))  # {1, 2, 3, 4, 5}

setで一瞬で重複削除。


10. リストを文字列に結合

lst = ["P", "y", "t", "h", "o", "n"]
print(''.join(lst))  # Python

文字列操作に必須テクニック。


💡 まとめ
これらのワンライナーを覚えておくと、Pythonコードが短く、読みやすく、効率的になります。特にデータ処理やスクリプト作成で大活躍間違いなしです。

1
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
1
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?