List Comprehension
List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.
์๋ฅผ ๋ค์ด๋ณด์.
Without list comprehension you will have to write a for statement with a conditional test inside:
Example
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
With list comprehension you can do all that with only one line of code:
Example
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist)
The Syntax
newlist = [expression for item in iterable if condition == True]
expression ๋ถ๋ถ์๋ ์ค์ง์ ์ผ๋ก ์ถ๋ ฅ๋๋ ๊ฐ๊ณผ ๊ด๋ จ๋ ๋ด์ฉ์ ์์ฑ (if๋ฌธ์ด ์ฌ์๋, ๋ค๋ฅธ ํ ์คํธ๋ก ๋์นํ ์๋ ์์)
codition ๋ถ๋ถ์๋ ์ด ์ ์ฒด ๋ฌธ์ฅ์ ๋ํ ์กฐ๊ฑด์ ์ด ์ฌ ์ ์์
๊ด๋ จ ์์ ์ฐธ๊ณ ํ์ด์ง : https://www.w3schools.com/python/python_lists_comprehension.asp
์ผํญ ์ฐ์ฐ์
์ผ๋ฐ์ ์ธ if ~ else ๋ฌธ์ ํตํด์ ํด๊ฒฐํ ์ ์๋ ์ฐ์ฐ์ "ํ ์ค๋ก ๊ฐ๋จํ๊ณ ๊ฐ๊ฒฐํ๊ฒ" ๋ํ๋ผ ์ ์๋ค.
The Syntax
(True) if (Condition) else (False)
# ์ง์์ธ์ง ํ์์ธ์ง ํ๋จํ๋ ์์
a = 10
# ์ผํญ ์ฐ์ฐ
print("even") if a % 2 == 0 else print("odd")
# ๊ธฐ๋ณธ ์ฐ์ฐ
if a % 2 == 0:
print("even")
else:
print("odd")
'Coding > Python' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Python] ์ฐ์ต๋ฌธ์ (๋ฌธ์ฅ ๋ง๋ค๊ธฐ) (0) | 2021.12.30 |
---|---|
[Python] *args, **kwargs (0) | 2021.12.30 |
[python] ๋ชจ๋ (0) | 2021.11.10 |
[python] ์์ธ์ฒ๋ฆฌ ํด์ฆ (0) | 2021.11.04 |
[python] ์์ธ ์ฒ๋ฆฌ (0) | 2021.11.04 |