[Python] List Comprehension๐Ÿ“–

Inah-_-ยท2021๋…„ 3์›” 24์ผ
0

Python

๋ชฉ๋ก ๋ณด๊ธฐ
19/21
post-thumbnail

Python List๐Ÿ“‹


Pythonicํ•˜๊ฒŒ List๋งŒ๋“ค๊ธฐ

[ ํ‘œํ˜„์‹ for ์›์†Œ in ๋ฐ˜๋ณต๊ฐ€๋Šฅํ•œ ๊ฐ์ฒด ]
[ ํ‘œํ˜„์‹ for ์›์†Œ in ๋ฐ˜๋ณต๊ฐ€๋Šฅํ•œ ๊ฐ์ฒด if๋ฌธ]

๊ธฐ์กด ์‚ฌ์šฉํ–ˆ๋˜ For๋ฌธ

๋นˆ list๋ฅผ ์ƒ์„ฑ ํ›„ for๋ฌธ์„ ๋Œ๋ ค append()

result = []

for num in range(1,11):
    result.append(num)

print(result)

# output
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# ์กฐ๊ฑด์ด ์žˆ๋Š” ํ‘œํ˜„์‹์ผ ๊ฒฝ์šฐ
result = []

for num in range(1,11):
    if num > 5:
        result.append(num)

print(result)

# output
[6, 7, 8, 9, 10]

List Comprehension

result = [ num for num in range(1,11) ]

print(result)

# output
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# ์กฐ๊ฑด์ด ์žˆ๋Š” ํ‘œํ˜„์‹์ผ ๊ฒฝ์šฐ
result = [ num for num in range(1,11) if num > 5 ]

print(result)

# output
[6, 7, 8, 9, 10]
profile
Backend Developer

0๊ฐœ์˜ ๋Œ“๊ธ€