Pythonの32周年のための32の必須Pythonワンライナー
1994年1月、グイド・ヴァンロッサムはUsenetの投稿を通じて世界に向けてPython 1.0を発表し、「読みやすい構文」を持つ言語を提供し、「先週書いたPerlのコードを解読する」手間から開発者を救うと約束しました。
30年後、Pythonは世界で最も広く使われているプログラミング言語の一つとなりました。Pythonの32周年を記念して、ここにPythonの実用的なワンライナー32選を紹介します。これらは、Pythonのシンプルさと明確さが今も重要である理由を示しています。
注意:いくつかの例では、有用性を優先して「ワンライナー」のルールを少し曲げています。ここでの目標はコードゴルフではなく、明確さです。
1. 2つの変数を交換する
a, b = b, a一時的な変数は不要です。Pythonのタプルのアンパッキングのおかげで、これは非常に簡単になります。
試してみて:
Pythonコンソールから、次のコードを実行してください:
>>> a, b = 5, 10
>>> print(f"Before: a={a}, b={b}")
Before: a=5, b=10
>>> a, b = b, a
>>> print(f"After: a={a}, b={b}")
After: a=10, b=52. 文字列を反転する
reversed_string = original[::-1]ステップが-1のスライス表記は魔法のように見える。
試してみて:
>>> original = "Ostechnix"
>>> reversed_string = original[::-1]
>>> print(reversed_string)
xinhcetsO3. 文字列が回文かどうか確認する
is_palindrome = text == text[::-1]文字列の反転と比較を組み合わせて、即座に回文を検出します。
試してみて:
>>> text = "racecar"
>>> is_palindrome = text == text[::-1]
>>> print(is_palindrome)
True
>>> text = "ostechnix"
>>> print(text == text[::-1])
False4. ネストされたリストを平坦化する
flat = [item for sublist in nested_list for item in sublist]リスト内包表記は、フラット化をエレガントで読みやすくします。
試してみて:
>>> nested_list = [[1, 2], [3, 4], [5, 6]]
>>> flat = [item for sublist in nested_list for item in sublist]
>>> print(flat)
[1, 2, 3, 4, 5, 6]5. ユニークな要素を見つける
unique = list(set(my_list))セットに変換して戻す。Pythonの集合論の実践。
試してみて:
>>> my_list = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
>>> unique = list(set(my_list))
>>> print(unique)
[1, 2, 3, 4]6. ファイルをリストに読み込む
lines = open('file.txt').read().splitlines()
ディスクからメモリに移すのは一行で済みます(ただし、本番コードではwithを使うのを忘れないでください!)。
試してみて:
>>> # First create a test file
>>> with open('test.txt', 'w') as f:
... f.write("Line 1\nLine 2\nLine 3")
>>> lines = open('test.txt').read().splitlines()
>>> print(lines)
['Line 1', 'Line 2', 'Line 3']7. 最も一般的な要素を見つける
most_common = max(set(my_list), key=my_list.count)カスタムキー関数と一緒にmax()を賢く使う方法。小さなリストではよく機能します。大きなデータにはCounterを使ってください。
試してみて:
>>> my_list = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
>>> most_common = max(set(my_list), key=my_list.count)
>>> print(most_common)
48. 行列を転置する
transposed = list(zip(*matrix))ここでの重労働は、* アンパッキング演算子が行います。
試してみて:
>>> matrix = [[1, 2, 3], [4, 5, 6]]
>>> transposed = list(zip(*matrix))
>>> print(transposed)
[(1, 4), (2, 5), (3, 6)]
>>> # Convert tuples to lists if needed
>>> print([list(row) for row in transposed])
[[1, 4], [2, 5], [3, 6]]9. 2つのリストから辞書を作成する
my_dict = dict(zip(keys, values))zip() はリストを結びつける接着剤です。
試してみて:
>>> keys = ['a', 'b', 'c']
>>> values = [1, 2, 3]
>>> my_dict = dict(zip(keys, values))
>>> print(my_dict)
{'a': 1, 'b': 2, 'c': 3}10. 順序を保持しながら重複を削除する
unique_ordered = list(dict.fromkeys(my_list))Python 3.7以降、辞書は挿入順を保持するようになり、これは祝う価値のある機能です!
試してみて:
>>> my_list = [3, 1, 2, 1, 3, 4, 2, 5]
>>> unique_ordered = list(dict.fromkeys(my_list))
>>> print(unique_ordered)
[3, 1, 2, 4, 5]11. 要素のすべてのインデックスを見つける
indices = [i for i, x in enumerate(my_list) if x == target]
一行できれいに列挙してフィルタリングする。
試してみて:
>>> my_list = [1, 2, 3, 2, 4, 2, 5]
>>> target = 2
>>> indices = [i for i, x in enumerate(my_list) if x == target]
>>> print(indices)
[1, 3, 5]12. 任意/全ての項目が条件に一致するか確認する
has_even = any(x % 2 == 0 for x in numbers)
all_positive = all(x > 0 for x in numbers)any() と all() 関数は、ジェネレーター式と組み合わせると非常に強力です。
試してみて:
>>> numbers = [1, 2, 3, 4, 5]
>>> has_even = any(x % 2 == 0 for x in numbers)
>>> print(has_even)
True
>>> all_positive = all(x > 0 for x in numbers)
>>> print(all_positive)
True13. 辞書を値で並べ替える
sorted_dict = dict(sorted(my_dict.items(), key=lambda x: x[1]))ラムダ関数はカスタムソートを簡単にします。
試してみて:
>>> my_dict = {'a': 3, 'b': 1, 'c': 2}
>>> sorted_dict = dict(sorted(my_dict.items(), key=lambda x: x[1]))
>>> print(sorted_dict)
{'b': 1, 'c': 2, 'a': 3}14. 2つの辞書を結合する
merged = {**dict1, **dict2}辞書のアンパッキング演算子(Python 3.5以降)は簡潔で明確です。
試してみて:
>>> dict1 = {'a': 1, 'b': 2}
>>> dict2 = {'c': 3, 'd': 4}
>>> merged = {**dict1, **dict2}
>>> print(merged)
{'a': 1, 'b': 2, 'c': 3, 'd': 4}15. イテレータから最初のN項目を取得する
first_n = list(itertools.islice(iterator, n))itertools.islice() は、すべてをメモリに読み込むことなく、任意のイテレータで動作します。
試してみて:
>>> import itertools
>>> iterator = iter(range(100))
>>> first_n = list(itertools.islice(iterator, 5))
>>> print(first_n)
[0, 1, 2, 3, 4]16. カウンター/頻度マップを作成する
from collections import Counter; freq = Counter(my_list)Counter クラスは、頻度カウントのためのスイスアーミーナイフです。
試してみて:
>>> from collections import Counter
>>> my_list = ['a', 'b', 'a', 'c', 'b', 'a']
>>> freq = Counter(my_list)
>>> print(freq)
Counter({'a': 3, 'b': 2, 'c': 1})
>>> print(freq.most_common(2))
[('a', 3), ('b', 2)]17. リストAにはあるがリストBにはない要素を見つける
difference = list(set(list_a) - set(list_b))集合演算により、これは直感的で高速になります。
試してみて:
>>> list_a = [1, 2, 3, 4, 5]
>>> list_b = [3, 4, 5, 6, 7]
>>> difference = list(set(list_a) - set(list_b))
>>> print(difference)
[1, 2]18. リストのすべての順列を取得する
from itertools import permutations; perms = list(permutations(my_list))itertools は組み合わせの爆発を処理してくれます。
試してみて:
>>> from itertools import permutations
>>> my_list = [1, 2, 3]
>>> perms = list(permutations(my_list))
>>> print(perms)
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]19. JSONをきれいに表示する
import json; print(json.dumps(data, indent=2))即座に人間が読みやすいJSON形式にする。
試してみて:
>>> import json
>>> data = {'name': 'Python', 'age': 32, 'features': ['readable', 'powerful']}
>>> print(json.dumps(data, indent=2))
{
"name": "Python",
"age": 32,
"features": [
"readable",
"powerful"
]
}20. 階乗を計算する
from math import factorial; result = factorial(n)あるいは、もしちょっと凝りたいなら:result=eval('*'.join(map(str, range(1, n+1))))
試してみて:
>>> from math import factorial
>>> result = factorial(5)
>>> print(result)
120
>>> # The fancy way
>>> n = 5
>>> result = eval('*'.join(map(str, range(1, n+1))))
>>> print(result)
12021. 1行でFizzBuzz
['Fizz'*(i%3==0) + 'Buzz'*(i%5==0) or str(i) for i in range(1,101)]文字列の掛け算とブール論理で解決された古典的な面接の質問。
試してみて:
>>> fizzbuzz = ['Fizz'*(i%3==0) + 'Buzz'*(i%5==0) or str(i) for i in range(1,21)]
>>> print(fizzbuzz)
['1', '2', 'Fizz', '4', 'Buzz', 'Fizz', '7', '8', 'Fizz', 'Buzz', '11', 'Fizz', '13', '14', 'FizzBuzz', '16', '17', 'Fizz', '19', 'Buzz']22. 複数のリストの共通部分を見つける
intersection = list(set.intersection(*map(set, list_of_lists)))集合論は、洗練された複数リストの交差のためのアンパッキングに出会う。
試してみて:
>>> list_of_lists = [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]]
>>> intersection = list(set.intersection(*map(set, list_of_lists)))
>>> print(intersection)
[3, 4]23. 文字列をタイトルケースに変換する(安全に)
title = ' '.join(word.capitalize() for word in text.split())アポストロフィを正しく処理できるので、.title()より優れています。
試してみて:
>>> text = "python's awesome one-liners"
>>> title = ' '.join(word.capitalize() for word in text.split())
>>> print(title)
Python's Awesome One-liners
>>> # Compare with .title()
>>> print(text.title())
Python'S Awesome One-Liners24. 浮動小数点で範囲を作成する
float_range = [x * 0.1 for x in range(10, 100)]リスト内包表記は range() の整数制限を克服します。
試してみて:
>>> float_range = [x * 0.1 for x in range(10, 20)]
>>> print(float_range)
[1.0, 1.1, 1.2000000000000002, 1.3, 1.4000000000000001, 1.5, 1.6, 1.7000000000000002, 1.8, 1.9000000000000001]25. ウェブからファイルをダウンロードする
import urllib.request; urllib.request.urlretrieve(url, 'filename.ext')インターネットからファイルを一行で取得する。
試してみて:
>>> import urllib.request
>>> url = 'https://www.python.org/static/img/python-logo.png'
>>> urllib.request.urlretrieve(url, 'python-logo.png')
('python-logo.png', <http.client.HTTPMessage object at 0x...>)
>>> # File is now saved as 'python-logo.png'26. ランダムなパスワードを生成する
import secrets, string; pwd = ''.join(secrets.choice(string.ascii_letters + string.digits) for _ in range(16))標準ライブラリを使用した安全なランダムパスワードの生成。
試してみて:
>>> import secrets, string
>>> pwd = ''.join(secrets.choice(string.ascii_letters + string.digits) for _ in range(16))
>>> print(pwd)
Kx9mP2nLq8WzBv3Y
>>> # Each run generates a cryptographically secure password
>>> pwd = ''.join(secrets.choice(string.ascii_letters + string.digits) for _ in range(16))
>>> print(pwd)
a7QnM5tR1wJzXp4G27. コードの実行時間を測る(簡単な確認)
import time; start = time.time(); your_function(); elapsed = time.time() - start手早く簡単なパフォーマンス測定(本格的なベンチマークにはtimeitを使用)。
試してみて:
>>> import time
>>> start = time.time()
>>> sum(range(1000000)) # Some operation to time
499999500000
>>> elapsed = time.time() - start
>>> print(f"Execution time: {elapsed:.6f} seconds")
Execution time: 15.000495 seconds28. 正規表現で全ての出現箇所を見つける
import re; matches = re.findall(pattern, text)正規表現はパターンマッチングを容易にします。
試してみて:
>>> import re
>>> text = "Python 1.0, Python 2.0, Python 3.0"
>>> pattern = r'Python \d+\.\d+'
>>> matches = re.findall(pattern, text)
>>> print(matches)
['Python 1.0', 'Python 2.0', 'Python 3.0']29. シンプルなHTTPサーバーを作成する
python -m http.server 8000さて、これは技術的にはコマンドラインのワンライナーですが、含めないわけにはいかないほど便利です!
試してみて:
# Run this in your terminal
$ python -m http.server 8000
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
# Then visit http://localhost:8000 in your browser
# Perfect for quickly sharing files or testing web pages locally30. 連鎖比較演算子
is_valid = 0 <= value <= 100Pythonは、考えるように数学を書くことを可能にします。
試してみて:
>>> value = 50
>>> is_valid = 0 <= value <= 100
>>> print(is_valid)
True
>>> value = 150
>>> print(0 <= value <= 100)
False
>>> # You can chain any comparison operators
>>> x = 5
>>> print(1 < x < 10)
True31. リストのデカルト積を取得する
from itertools import product; pairs = list(product(list1, list2))ネストされたループなしで、すべての組み合わせを生成する。
試してみて:
>>> from itertools import product
>>> list1 = ['A', 'B']
>>> list2 = [1, 2]
>>> pairs = list(product(list1, list2))
>>> print(pairs)
[('A', 1), ('A', 2), ('B', 1), ('B', 2)]
>>> # Works with any number of lists
>>> print(list(product(['X', 'Y'], [1, 2], ['a', 'b'])))
[('X', 1, 'a'), ('X', 1, 'b'), ('X', 2, 'a'), ('X', 2, 'b'), ('Y', 1, 'a'), ('Y', 1, 'b'), ('Y', 2, 'a'), ('Y', 2, 'b')]32. クイックなラムダサーバーを作成する(本当に!)
from flask import Flask; app = Flask(__name__); app.route('/')(lambda: 'Hello!')本番環境には推奨されませんが、Flaskの簡単さを示しています!
試してみて:
>>> from flask import Flask
>>> app = Flask(__name__)
>>> @app.route('/')
... def hello():
... return 'Hello, Python is 32!'
>>> # Then run: app.run()
# Visit http://localhost:5000 to see your message
# Note: You'll need Flask installed: pip install flaskパイソンの霊
これらの一行コードは、賢くあることを目的としたものではありません。それらは Python の長年の価値観を反映しています:
- トリックより可読性
- 露骨な行動
- 強力な標準ライブラリ
- 自分自身を説明するコード
1994年にグイドがPython 1.0を発表したとき、彼は読みやすい言語を約束しました。32年後、Pythonはその約束を今も守り続けています。
パイソン、32周年おめでとうございます!
あなたのお気に入りのPythonのワンライナーは何ですか?ぜひ下のコメントでシェアしてください!
さらに読む:
- UsenetでのオリジナルPython 1.0発表
- Pythonの禅
- Python の公式ドキュメント
