Qiita Teams that are logged in
You are not logged in to any team

Community
Service
Qiita JobsQiita ZineQiita Blog
3
Help us understand the problem. What is going on with this article?
@hikurochan

# 内包表記

More than 1 year has passed since last update.

## リスト内包表記

```l = []
for i in range(10):
if i % 2 == 0:
l.append(i)
print(l)
```

```l = [i for i in range(10) if i % 2 ==0]
print(l)
```

```[0, 2, 4, 6, 8]
```

## 辞書内包表記

```w = ['Monday', 'Tuesday','Friday']
f = ['banana', 'apple', 'orange']
d= {}
for x, y in zip(w,f):
d[x]=y
print(d)
```

```w = ['Monday', 'Tuesday','Friday']
f = ['banana', 'apple', 'orange']
d = {x:y for x,y in zip(w,f)}
print(d)
```

```{'Monday': 'banana', 'Tuesday': 'apple', 'Friday': 'orange'}
```

## 集合内包表記

```s = set()
for i in range(10):
if i % 2 == 0:
print(s)
```

```s = {i for i in range(10) if i % 2 == 0}
print(s)
```

```{0, 2, 4, 6, 8}
```

## ジェネレータ式

```def g():
for i in range(10):
if i % 2 == 0:
yield i
g = g()
print(next(g))
print(next(g))
print(next(g))
print(next(g))
```

```g = (i for i in range(10) if i % 2 == 0)
print(next(g))
print(next(g))
print(next(g))
print(next(g))
```

```0
2
4
6
```

なお、公式ドキュメントに「ジェネレータ表記法」と書いてあり「ジェネレータ内包表記」ではない。
https://docs.python.org/ja/3/reference/expressions.html#generator-expressions

ジェネレータ式 (generator expression) とは、丸括弧を使ったコンパクトなジェネレータ表記法です:
ジェネレータ式は新たなジェネレータオブジェクトを与えます。この構文は内包表記とほぼ同じですが、角括弧や波括弧ではなく、丸括弧で囲まれます。

3
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
1. We will deliver articles that match you
By following users and tags, you can catch up information on technical fields that you are interested in as a whole
2. you can read useful information later efficiently
By "stocking" the articles you like, you can search right away