0
1

More than 3 years have passed since last update.

Python3のmap/filterがiteratorを返してることの意味

Last updated at Posted at 2019-10-28

Python3でmap/filterがイテレータを返すことは知っていたが、トラップにはまってしまったのでメモ

lst = [1,2,3,4,5]

flist = filter(lambda i: i%2==0, lst)
print(flist)

for i in flist:
    print(i)

for i in flist:
    print(i)

python2系で実行すると

[2, 4]
2
4
2
4

python3系で実行すると

<filter object at 0x7f1d6636e518>
2
4

イテレータを一度ループさせて終端まで行ってるのでもう一度適用しても何も残ってないですよ、というお話

flist = list(filter(lambda i: i%2==0, lst))

と書かないといけない

0
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
0
1