0
0

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.

複数条件のin演算子の内包表記

Posted at

概要

こんにちはkentoです。初投稿です。

python の if文を使ってリスト(配列)の中に特定の要素が存在するか、存在しないかを判別するときに
複数の要素で分類したいときに用いる内包表記はどのようにしたらと試行錯誤した結果、このようにすれば分類できました。

内容

if文の中で複数条件を用いる中で
orandを使用するかと思います。
そのほかにもpythonには
anyallなどの関数もあります。

例えば

sample =  ['Humidity']
print('temperature' in sample or 'Humidity' in  sample or'carbon dioxide' in sample or 'Atmospheric pressure' in sample)
print(any(['temperature' in sample,'Humidity' in sample,'carbon dioxide' in sample,'Atmospheric pressure' in sample]))

# => True
# => True


sample =  ['Humidity']
print('temperature' in sample and 'Humidity' and  sample and'carbon dioxide' in sample and 'Atmospheric pressure' in sample)
print(all(['temperature' in sample,'Humidity' in sample,'carbon dioxide' in sample,'Atmospheric pressure' in sample]))
# => False
# => False

となるかと思います。しかしin 関数の中で複数のorandが存在する場合は以下のように内包表記できます。

sample =  ['Humidity','carbon dioxide']
print(all([any(['temperature' in sample,'Humidity' in sample]),any(['carbon dioxide' in sample,'Atmospheric pressure' in sample])]))

# => True


sample =  ['Humidity','temperature']
print(all([any(['temperature' in sample,'Humidity' in sample]),any(['carbon dioxide' in sample,'Atmospheric pressure' in sample])]))

# => False

よってこのif文に組み込むとを使うと

sample =  ['carbon dioxide','temperature']
if all([any(['temperature' in sample,'Humidity' in sample]),any(['carbon dioxide' in sample,'Atmospheric pressure' in sample])]):
    print("ok")

# => ok

となります。

まとめ

Pythonでリスト(配列)の中に特定の要素を分類したい場合は使用してみてください
コメント等あれば、この記事にコメントお願いします。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?