Python ๋ด์ฅ ํจ์ all()์ ์ดํด์ ์ฌ์ฉ๋ฒ
1. ์ ์
`all()` ํจ์๋ ํ์ด์ฌ์ ๋ด์ฅ ํจ์ ์ค ํ๋๋ก, ์ธ์๋ก ์ฃผ์ด์ง iterable(๋ฐ๋ณต ๊ฐ๋ฅํ ๊ฐ์ฒด)์ ๋ชจ๋ ์์๊ฐ ์ฐธ(True)์ผ ๋ `True`๋ฅผ ๋ฐํ
ํ๊ณ , ํ๋๋ผ๋ ๊ฑฐ์ง(False)์ด ์๋ค๋ฉด `False`๋ฅผ ๋ฐํํ๋ค.
2. ๋ฌธ๋ฒ
- `iterable`: ๋ฆฌ์คํธ(list), ํํ(tuple), ์งํฉ(set), ๋์
๋๋ฆฌ(dict), ๋ฌธ์์ด(string) ๋ฑ ๋ฐ๋ณต ๊ฐ๋ฅํ ๊ฐ์ฒด(iterable)๋ฅผ ๋ฃ๋๋ค.
3. ๋ฐํ๊ฐ
์กฐ๊ฑด๋ฐํ๊ฐ
๋ชจ๋ ์์๊ฐ True์ธ ๊ฒฝ์ฐ |
`True` |
ํ๋๋ผ๋ False์ธ ๊ฒฝ์ฐ |
`False` |
๋น iterable |
`True` (์ฃผ์!) |
- ์ฃผ์: `all()`์ ๋น iterable์ ์
๋ ฅ๋ฐ์ผ๋ฉด ํญ์ `True`๋ฅผ ๋ฐํํ๋ค. (๋น iterable ์์ `False` ์์๊ฐ ์๊ธฐ ๋๋ฌธ)
4. ํ์ฉ ์์
์์ 1: ๊ธฐ๋ณธ ์ฌ์ฉ๋ฒ
print(all([True, True, True])) # True
print(all([True, False, True])) # False
์์ 2: ์กฐ๊ฑด๋ฌธ๊ณผ ํจ๊ป ์ฌ์ฉํ๊ธฐ
numbers = [1, 3, 5, 7, 9]
# ๋ชจ๋ ์ซ์๊ฐ ํ์์ธ์ง ํ์ธ
is_all_odd = all(num % 2 == 1 for num in numbers)
print(is_all_odd) # True
์์ 3: ๋ฌธ์์ด, ๋น ๊ฐ์ฒด์์ ์ฌ์ฉ๋ฒ
print(all("hello")) # True, ๋ชจ๋ ๋ฌธ์๋ ๋น์ด์์ง ์์ True๋ก ํ๊ฐ๋จ
print(all("")) # True, ๋น iterable
print(all([0, 1, 2])) # False, 0์ False๋ก ํ๊ฐ๋จ
print(all([])) # True, ๋น iterable
์์ 4: ๋ฆฌ์คํธ ๋ด ๋ชจ๋ ๊ฐ์ด ํน์ ๋ฌธ์์ด์ ์๋์ง ๊ฒ์ฌํ ๋ ํ์ฉ
spell = ['a', 'e', 'i']
word = "alphabet"
result = all(s in word for s in spell)
print(result) # False ('i'๊ฐ ์์ผ๋ฏ๋ก False ๋ฐํ)
5. ์์ฃผ ์ฐ์ด๋ ํจํด
# ๋ฆฌ์คํธ ์์๊ฐ ๋ชจ๋ ํน์ ์กฐ๊ฑด์ ๋ง์กฑํ๋์ง ๊ฒ์ฌ
if all(condition(x) for x in iterable):
# ๋ชจ๋ ์์๊ฐ ์กฐ๊ฑด์ ๋ง์กฑํ ๋ ์คํํ ์ฝ๋
scores = [85, 92, 88, 79]
if all(score >= 70 for score in scores):
print("๋ชจ๋ ํ์์ด ํฉ๊ฒฉํ์ต๋๋ค.")
else:
print("ํ๋ฝ์๊ฐ ์์ต๋๋ค.")
6. ์ฃผ์์ฌํญ
- `all()`์ ๋จ์ถ ํ๊ฐ(short-circuit) ๋ฐฉ์์ผ๋ก ๋์ํ๋ค.
- ์ฆ, ํ๋์ ์์๋ผ๋ `False`๊ฐ ๋ํ๋๋ฉด ๊ทธ ์ฆ์ ํ๊ฐ๋ฅผ ๋ฉ์ถ๊ณ `False`๋ฅผ ๋ฐํํ๋ค.
- ๋น iterable์์ `True`๋ฅผ ๋ฐํํ๋ ํน์ฑ์ ์ดํดํ๊ณ ํ์ฉํด์ผ ํ๋ค.
7. ์์ฝ
- ํ์ด์ฌ์ ๋ด์ฅ ํจ์ `all()`์ iterable ๊ฐ์ฒด์ ๋ชจ๋ ์์๊ฐ ์ฐธ์ผ ๋ `True`, ํ๋๋ผ๋ ๊ฑฐ์ง์ด๋ฉด `False` ๋ฐํ
- ๋น iterable์ ๋ํด์๋ ํญ์ `True` ๋ฐํ
- ์กฐ๊ฑด์ ์ฒดํฌํ ๋ ๊ฐ๋จํ๊ณ ๋ช
๋ฃํ ์ฝ๋๋ฅผ ์์ฑํ ์ ์๊ฒ ํด์ฃผ๋ ์ ์ฉํ ํจ์์ด๋ค.