# 리스트를 만들어서 던짐
def squareList(nums):
result = []
for n in nums: result.append(n * n)
return result
myNums = squareList([1, 2, 3, 4, 5])
print(myNums)
# 결과
[1, 4, 9, 16, 25]
# yield를 사용해 객체를 던짐
def squareList(nums):
for n in nums: yield (n * n)
myNums = squareList([1, 2, 3, 4, 5])
for n in myNums:
print(n, end = ' ')
# 결과
1 4 9 16 25
# flatten list
nested_ls = [[1, 2], [3, 4], [5]]
def flatten(nested):
for sublist in nested:
for ele in sublist:
yield ele
o = flatten(nested_ls)
print(list(o))
# 결과
[1, 2, 3, 4, 5]
# flatten list with comprehension, generator
nested_ls = [[1, 2], [3, 4], [5]]
flat = (x for sublist in nested_ls for x in sublist)
print(list(flat))
# 결과
[1, 2, 3, 4, 5]
# flatten multiple list
def flatten_smart(nested):
try:
for sublist in nested:
for ele in flatten_smart(sublist):
yield ele
except TypeError:
yield nested
nested_ls = [[[1], 2], 3, 4, [5, [6, 7]], 8]
o = flatten_smart(nested_ls)
print(list(o))
# 결과
[1, 2, 3, 4, 5, 6, 7, 8]
# Consider generators instead of returning lists
def index_words(text: str) -> list[str]:
result: list[str] = []
if text:
result.append(0) # first position
for idx, letter in enumerate(text):
if letter == ' ':
result.append(idx + 1)
return result
address: str = "Four score and evene years ago our fathers brought forth on this continent a new nation, conceived in liberty, and dedicated to the proposition that all men are created equal."
# result: list[int] = index_words(address)
# print(result[:3])
# print(result)
# generator version of the function
# 리스트는 리턴하는 것보다 제너레이터로 구현하는 것이 깔끔하기는 하다.
# 매우 많은 데이터를 하나의 리스트에 넣는 과정이 메모리 소모가 심할 수 있다.
def index_words_gr(text):
if text:
yield 0
for idx, letter in enumerate(text):
if letter == ' ':
yield idx + 1
it = index_words_gr(address)
print(list(it))
# 결과
[0, 5, 11, 15, 21, 27, 31, 35, 43, 51, 57, 60, 65, 75, 77, 81, 89, 99, 102, 111, 115, 125, 128, 132, 144, 149, 153, 157, 161, 169]
from typing import Generator
def get_even(nums: list[int]) -> Generator [int]:
for num in nums:
if num % 2 == 0:
yield num
nums: list[int] = [n for n in range(1, 101)]
even_gen = get_even(nums)
print(list(even_gen))
# 결과
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100]
댓글 영역