Coding/Python

[python] list Comprehension, ์‚ผํ•ญ ์—ฐ์‚ฐ์ž

๊น€์œ ๋‹ˆ์ฝ˜ 2021. 12. 29. 16:24

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

 

Python - List Comprehension

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

 

 

์‚ผํ•ญ ์—ฐ์‚ฐ์ž 

์ผ๋ฐ˜์ ์ธ 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