1
3

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 5 years have passed since last update.

No.038【Python】組み込み関数:all( )/any( )について

Last updated at Posted at 2019-02-21

python-logo-master-v3-TM-flattened.png

今回は、組み込み関数「all()・any()」について書いていきます。

I'll write about built-in functions, "all () and any()" in python" on this page.

■ all()とany()の使い方

 How to use all() and any()

>>> # all() と any()の使用:
>>> #イテラブルオブジェクトの要素が全てTrue or False, いずれかがTrueかを判定するため

■ 全ての要素がTrueかを判定する:all()

 Judging all elements areTrue or not

>>> print(all([True, True, True]))
True
>>> 
>>> print(all([True, False, True]))
False
>>> # タプル・set型も引数に指定することが可能
>>> 
>>> print(all((True,True,True)))
True
>>> 
>>> print(all({True,True,True}))
True
>>> # bool型のTrue,
>>> # bool型のTrue, Falseだけでなく他の型も判定し、結果を返す
>>> 
>>> 
>>> print(all([100, [0, 1, 2, 3, 4], "abcde"]))
True
>>> 
>>> print(all([100, [0, 1, 2, 3, 4], "abcde", {}]))
False

■ いずれかがTrueかどうかを判定:any()

 Judging some elements are True or not

>>> print(any([True, False, False]))
True
>>> 
>>> print(any([False, False, False]))
False
>>> # ↑ 全てがFalseの場合は、Falseを返す
>>> # タプルやset型も引数に指定することが可能
>>> 
>>> print(any((True, False, False)))
True
>>> print(any({True, False, False}))
True

■ # すべての要素がFalseかどうかを判定:not any()

 Judging all elements are False or not

>>> print(not any([False, False, False]))
True
>>> 
>>> print(not any([True, False, False]))
False

■ 条件に対する判定: リスト内包表記/ジェネレータ

 Judging to conditions:list comprehension / generator

>>> # リスト内包表記:任意条件に対し、all()やany()の適用が可能
>>> 
>>> l = [0, 1, 2, 3, 4]
>>> 
>>> print([i > 2 for i in l])
[False, False, False, True, True]
>>> # 上記結果をall()またはany()の引数に指定
>>> # 全てまたはいずれかの条件を満たすか判定が可能
>>> 
>>> print(all([i > 2 for i in l]))
False
>>> 
>>> print(any([i > 2 for i in l]))
True
>>> 
>>> 
>>> print(type([i > 2 for i in l]))
<class 'list'>
>>> 
>>> 
>>> print(type(i > 2 for i in l))
<class 'generator'>
>>> # ↑ [ ]を( )へかけることでジェネレータ式となる
>>> #ジェネレーター式を all(), any()の引数に指定可能
>>> 
>>> print(all(i > 2 for i in l))
False
>>> 
>>> 
>>> print(any(i > 2 for i in l))
True
>>> # True = 1 , False = 0として処理される
>>> # sum を使うとTrueの数を取得することができる
>>> 
>>> print(sum(i > 2 for i in l))
2
>>> 
>>> # Falseを数える場合は、notを使用する
>>> 
>>> print(sum(not( i > 2) for i in l))
3

随時に更新していきますので、
定期的な購読をよろしくお願いします。
I'll update my article at all times.
So, please subscribe my articles from now on.

本記事について、
何か要望等ありましたら、気軽にメッセージをください!
If you have some requests, please leave some messages! by You-Tarin

1
3
1

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
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?