Skip to content

Commit 3b588c0

Browse files
committed
Add docs
1 parent ae07325 commit 3b588c0

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

docs/ch02-06-list-comprehensions.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# リスト内包表記
2+
3+
リスト内包表記とはリストを簡単に作成するための構文のことです。今 `[0, 2, 4, 6, ..., 98]` というリストを作ろうとした場合、
4+
5+
```python
6+
x = []
7+
8+
for i in range(50):
9+
x.append(i * 2)
10+
```
11+
12+
のようにループ処理をして要素を詰めて作ることができますが、リスト内包表記を使うと下記のようにもっとシンプルに書くことができます。
13+
14+
```python
15+
x = [i * 2 for i in range(50)]
16+
```
17+
18+
リスト内包表記は別のコレクション型から変換を行う際によく使われます。例えば下記は辞書からタプルを要素とするリストを作成する例です。
19+
20+
```python
21+
x = {'a': 10, 'b': 20, 'c': 30}
22+
y = [(key, val) for key, val in x.items()] # [('a', 10), ('b', 20), ('c', 30)]
23+
```
24+
25+
ループ処理を短く書くことができますので活用するとコードがシンプルになります。

mkdocs.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ nav:
5252
- 2.3. コメント: ch02-03-comments.md
5353
- 2.4. 条件文: ch02-04-conditions.md
5454
- 2.5. ループ文: ch02-05-loops.md
55+
- 2.6. リスト内包表記: ch02-06-list-comprehensions.md
5556
- 3. クラス:
5657
- 3.1. クラス: ch03-01-classes.md
5758
- 4. モジュールとパッケージ:

0 commit comments

Comments
 (0)