1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Python itertoolsつかって多次元リストを1次元リストにしてリスト内包表記でforループさせたらリストが消えた!?

Last updated at Posted at 2022-02-24

itertoolsでchainして生成されるのはリストではなくて、itertools.chainクラス。こいつはジェネレータだから、forで最後までループさせると空になるまでnext()しちゃうって訳さ!

以下で動作確認をしてみるね!

import copy
import itertools

ls = [[1,2,3],[4,5,6]]

genr = itertools.chain.from_iterable(ls)

print(type(genr))

# 1が取り出される
print(next(genr))
# 2が取り出される
print(next(genr))

# この時点の要素
print(list(copy.deepcopy(genr)))
# ここでコピーせず、そのままprintすると
# 全要素がnext()されてしまうので注意
# print(list(copy.deepcopy(genr)))
# genr = [] になってしまう

# 奇数を取り出す例
pick_out_odd =[n for n in genr if n % 2 != 0]

print(pick_out_odd)

print(list(genr))
<class 'itertools.chain'>
1
2
[3, 4, 5, 6]
[3, 5]
[]
1
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?