33
24

More than 5 years have passed since last update.

[Python]List Comprehension リストの作り方いろいろ

Last updated at Posted at 2016-01-01

List Comprehension

List Comprehensionを使うとListの作成が簡単にかける。
Comprehensionは「理解」ではなく「含む」という意味で、日本語ではリストの内包表現などと言うらしい。

例）０～２９までの値のリストを作る

List Comprehensionを使用しない場合

``````In [1]: L1 = []
...: for x in range(30):
...:     L1.append(x**2)
...:
...: print(L1)
...:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841]
``````

List Comprehensionを使用した場合

いちいち空のListを作ってappendしなくても下のように１行でかける。

``````In [2]: L2 =[x**2 for x in range(30)]
In [3]: print(L2)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841]
``````

for文のあとにif文を続けることができる。

``````In [4]: L3 = [x for x in range(30) if x % 2 == 0]
In [5]: print(L3)
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28]
``````

for文のあとにfor文を続けることもできる。

``````In [6]: L4 = [(x,y) for x in range(10) for y in range(x,10)]
In [7]: print(L4)
[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7), (0, 8), (0, 9), (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (2, 7), (2, 8), (2, 9), (3, 3), (3, 4), (3, 5), (3, 6), (3, 7), (3, 8), (3, 9), (4, 4), (4, 5), (4, 6), (4, 7), (4, 8), (4, 9), (5, 5), (5, 6), (5, 7), (5, 8), (5, 9), (6, 6), (6, 7), (6, 8), (6, 9), (7, 7), (7, 8), (7, 9), (8, 8), (8, 9), (9, 9)]
``````

Generator Comprehension

[]を()にするとGeneratorが作成できる

``````In [8]: G4 = ((x,y) for x in range(10) for y in range(x,10))

In [9]: G4
Out[9]: <generator object <genexpr> at 0x000000000A395D80>

In [10]: L5 = list(G4)

In [11]: print(L5)
[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7), (0, 8), (0, 9), (1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6), (2, 7), (2, 8), (2, 9), (3, 3), (3, 4), (3, 5), (3, 6), (3, 7), (3, 8), (3, 9), (4, 4), (4, 5), (4, 6), (4, 7), (4, 8), (4, 9), (5, 5), (5, 6), (5, 7), (5, 8), (5, 9), (6, 6), (6, 7), (6, 8), (6, 9), (7, 7), (7, 8), (7, 9), (8, 8), (8, 9), (9, 9)]
``````

33
24
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
33
24