댓글 쓰기 권한이 없습니다. 로그인 하시겠습니까?
Python
2014.04.30 10:14
filter()와 reduce() 함수
조회 수 12919 댓글 0
Filter() - 리스트에서 조건에 맞는 멤버만 골라서 남겨줌 - filter(lambda x:x<'a', 'abcABCdefDEF') # 문자열 >> 'ABCDEF' - 함수를 아무것도 넘겨주지 않을 때에는 멤버 자체를 Boolean 테스트를 하게됨 - L = ['high', 'level', '', 'built-in', '', 'function'] filter(None, L) >> ['high', 'level', 'built-in', 'function'] # Suppose you have a list of people's first names. You want to reduce the list down to only those people whose first names start with "C". people = ['Amy', 'Alice', 'Bobby', 'Charlie', 'Connie', 'David'] # You would create a callback function that would look something like this: def starts_with_c(name): if name[0] == "C": return True return False # So then, you would run the filter function starts_with_c_list = filter(starts_with_c, people) print starts_with_c_list # prints ['Charlie', 'Connie'] Reduce() Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates((((1+2)+3)+4)+5). The left argument, x, is the accumulated value and the right argument, y, is the update value from the iterable. If the optional initializer is present, it is placed before the items of the iterable in the calculation, and serves as a default when the iterable is empty. If initializer is not given and iterable contains only one item, the first item is returned. Roughly equivalent to: Dreamy의 코드 스크랩내가 모으고 내가 보는
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Designed by sketchbooks.co.kr / sketchbook5 board skin
Sketchbook5, 스케치북5
Sketchbook5, 스케치북5
Sketchbook5, 스케치북5
Sketchbook5, 스케치북5