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】

Posted at

ただただ内包表記のサンプルを並べる

 初めて Python の内包表記を知ったとき、ネット上に転がるサンプルを真似して書いて覚えた記憶があったので、備忘録もかねてこの記事にサンプル転がしときます。一応解説も折りたたみであります。

 思いついたら随時更新予定。

ROT13

 13文字ずらす暗号をROT13と言います。

>>> alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # 文章に現れるアルファベット(今回は全部大文字)
>>> msg = "HELLOWORLD" # 暗号化したい文章
>>> ROT = 13 # ずらす文字数
>>> msg_ROT = [alphabet[(alphabet.index(i) + ROT) % len(alphabet)] for i in msg] # 内包表記
>>> msg_ROT
['U', 'R', 'Y', 'Y', 'B', 'J', 'B', 'E', 'Y', 'Q']
解説
>>> msg_ROT = [alphabet[(alphabet.index(i) + ROT) % len(alphabet)] for i in msg] # 内包表記

 後半の for i in msgmsg というオブジェクトの中を、変数 i で走査します、という意味。
 
 前段の alphabet[(alphabet.index(i) + ROT) % len(alphabet)] について、まずは一つずつ値を見ていきます。

  • alphabet.index(i) ... 変数 i にある文字が alphabet の何番目かを調べています。例えばalphabet.index("A")0alphabet.index("K")10 といった具合です。

  • ROT = 13 で、len(alphabet) は変数 alphabet の要素数なので 26 です。

 例えば (alphabet.index("A") + ROT) % len(alphabet)(0 + 13) % 2613 という数値になります。
 これを、変数 alphabet のインデックスにすると、alphabet[13]"N" とかってなります。

九九の表

>>> times_table = {f"{i}の段":[i * j for j in range(1, 10)] for i in range(1, 10)}
>>> times_table["3の段"]
[3, 6, 9, 12, 15, 18, 21, 24, 27]
>>> times_table["7の段"]
[7, 14, 21, 28, 35, 42, 49, 56, 63]

ピタゴラス数

>>> import itertools
>>> [(i, j, k) for i, j, k in itertools.combinations(range(20), 3) if i**2 + j**2 == k**2]
[(3, 4, 5), (5, 12, 13), (6, 8, 10), (8, 15, 17), (9, 12, 15)]

パスカルの三角形

>>> height = 20
>>> pascal = [[comb(i, k) for k in range(i + 1)] for i in range(height)]
>>> pascal[8]
[1, 8, 28, 56, 70, 56, 28, 8, 1]

素数列

>>> max_value = 100
>>> primes = [x for x in range(2, max_value) if all(x % d != 0 for d in range(2, int(x**0.5)+1))]
>>> primes
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
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?