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

PythonでFalseとTrueの取り扱い小技

Posted at

Pythonのリストで False の数を数えるには、いくつか方法があります。
今回はこのリストを使って、

l = [False, True, False, False, True]

「Falseはいくつある?」を2通りで解いてみます!
BooleanであるTrueとFalseの取り扱いに注目しましょう。


✅ パターン①:for文+カウント変数

l = [False, True, False, False, True]
count = 0
for i in l:
    if i == False:
        count += 1

print(f"Falseの数: {count}")  # → Falseの数: 3

✅ 特徴

  • 初心者向けで読みやすい!
  • ロジックが明確で、デバッグしやすい

✅ パターン②:sum()を使うテクニック

l = [False, True, False, False, True]
print(f"Trueの数: {sum(l)}")  # Trueの数: 2
print(f"Falseの数: {len(l) - sum(l)}")  # Falseの数: 3

✅ 特徴

  • True1False0 として数えられることを利用
    • pythonではTrueとFalseはそれぞれ1と0と同値であることを利用
  • 1行でスマートに計算できる!

✅ まとめ

方法 メリット デメリット
for文 読みやすい・やさしい 少し長い
sum() スマート・短い 最初はちょっと分かりにくいかも

参考記事

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