LoginSignup
4
4

More than 5 years have passed since last update.

Python のバージョン違いによる filter() の挙動に愕然としている

Last updated at Posted at 2014-02-14

Python 2.7.5 (default, Aug 25 2013, 00:04:04)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> data = 'spam123'
>>> bool(filter(lambda s:s.isupper(),data))
False
Python 3.3.3 (v3.3.3:c3896275c0f6, Nov 16 2013, 23:39:35)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> data = 'spam123'
>>> bool(filter(lambda s:s.isupper(),data))
True

詳しい方がいらっしゃったら解説してほしいです

解説していただけました!! 2014-02-15 10:10

http://qiita.com/trsqxyz/items/50e6e59e23995b6c2b41#comment-d01210d7bd8f60d2c590
filter()が2系でリストを返していたのが、3系ではイテレータを返すようになったのが原因のようです。

@shiena ありがとうございます!!

空のリストからイテレータオブジェクトに変わったためにブール値が変わってしまったんですね

ここらへんは Dive into Python 3 が便利そう

ということで


Python 3.3.3 (v3.3.3:c3896275c0f6, Nov 16 2013, 23:39:35) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> data = 'spam123'
>>> bool(list(filter(lambda s:s.isupper(),data)))
False

となりました
関数をひとつずつ検証するのは大事ですね

コメントしていただけました!! 2014-06-01 10:46

http://qiita.com/trsqxyz/items/50e6e59e23995b6c2b41#comment-945bff027756ad382a35
コード例のような処理を書きたい場合は、boolよりもanyが適しています。

any( ) は iterable な要素のいずれかが真であれば True を返す組み込み関数です。要素全ての場合は all( ) がありますね。

確かに any( ) を使うほうが適切に思えます。ありがとうございました。

any( )bool( )

>>> a=[0]
>>> bool(a)
True
>>> any(a)
False

any( ) は要素ごとにチェック bool( ) は要素があるのか という感じでしょうか

4
4
4

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
4
4