Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python any() และ all(): ตรวจสอบค่า True ใน Iterable

ฟังก์ชัน Built-in any() และ all() ใช้ตรวจสอบค่า Truthiness ใน Iterable (List, Tuple, Dict, String) any() คืน True ถ้ามีอย่างน้อย 1 ค่าเป็น True all() คืน True ถ้าทุกค่าเป็น True (หรือ Iterable ว่าง)

any() – มีค่า True อย่างน้อยหนึ่งค่า

any(iterable)
  • คืน True ถ้ามี Element อย่างน้อย 1 ตัว Evaluate เป็น True
  • คืน False ถ้าทุกตัวเป็น False หรือ Iterable ว่าง

ตัวอย่างกับ List

race_wins = [False, False, True, False]
print(any(race_wins))  # True (มี True อย่างน้อย 1)

ตัวอย่างกับ Dictionary

any(dict) ตรวจสอบ Key (ไม่ใช่ Value)

record = {'driver': 'John', 'year': 2018, 'top_ten': True}
print(any(record))  # True (Key ทั้งหมด Non-empty string = True)

ตัวอย่างกับ String

String ว่าง = False, String มีตัวอักษร = True

ranking = ""
print(any(ranking))  # False

all() – ทุกค่าเป็น True

all(iterable)
  • คืน True ถ้าทุก Element เป็น True หรือ Iterable ว่าง
  • คืน False ถ้ามี Element อย่างน้อย 1 ตัวเป็น False

ตัวอย่างกับ List

race_wins = [False, False, True, False]
print(all(race_wins))  # False (มี False อยู่)

ตัวอย่างกับ Dictionary

all(dict) ตรวจสอบ Key เช่นกัน

record = {'driver': 'John', 'year': 2018, 'top_ten': True}
print(all(record))  # True (Key ทุกตัว Truthy)

ตัวอย่างกับ String

name = "John Appleseed"
print(all(name))  # True (String ไม่ว่าง)

สรุป

Functionคืน True เมื่อคืน False เมื่อ
any()มี Element อย่างน้อย 1 ตัว Truthyทุกตัว Falsy หรือ Iterable ว่าง
all()ทุกตัว Truthy หรือ Iterable ว่างมี Element อย่างน้อย 1 ตัว Falsy

ใช้ any() ตรวจสอบ "มีอย่างน้อยหนึ่ง" และ all() ตรวจสอบ "ทุกอย่าง" ในเงื่อนไขโปรแกรม