Help us understand the problem. What is going on with this article?

内包表記

リスト内包表記

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:
        s.add(i)
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) とは、丸括弧を使ったコンパクトなジェネレータ表記法です:
ジェネレータ式は新たなジェネレータオブジェクトを与えます。この構文は内包表記とほぼ同じですが、角括弧や波括弧ではなく、丸括弧で囲まれます。

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
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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
ユーザーは見つかりませんでした