티스토리 뷰

Python

yield 사용법

techbard 2016. 4. 28. 18:38

# 리스트를 만들어서 던짐


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]


댓글
댓글쓰기 폼
공지사항
Total
411,813
Today
2
Yesterday
14
«   2020/01   »
      1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31  
글 보관함