[python] filter
๐ filter
python์ built-inํจ์๋ก ๋ฆฌ์คํธ๋ ๋์ ๋๋ฆฌ๊ฐ์ iterableํ ๋ฐ์ดํฐ๋ฅผ ์กฐ๊ฑด์ ๋ง๋ ๊ฐ๋ง ์ถ์ถํ ๋ ์ฌ์ฉํ๋ ํจ์์ด๋ค.
๐ต ์ฌ์ฉ๋ฒ
filter(function(ํจ์), iterable(๋ฆฌ์คํธ๋ ๋์ ๋๋ฆฌ๋ฑ)
๐น ํจ์๋ฅผ ๋ฃ์ด ์ฌ์ฉํ ๋
def func(x):
if x % 2 == 1:
return x
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
odd_lst = list(filter(func, lst))
print(odd_lst)
# >>> [1, 3, 5, 7, 9]
๐น lambda๋ก ์ฌ์ฉํ ๋
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
odd_lst = list(filter(lambda x: x % 2 == 1, lst))
print(odd_lst)
#>>> [1, 3, 5, 7, 9]
-lambda ์ฌ์ฉ๋ฒ์ด ์ต์ํ๊ณ ์กฐ๊ฑด์ด ๊ฐ๋จํ๋ค๋ฉด lambda๋ฅผ ์ฌ์ฉํ๋๊ฒ์ ์ถ์ฒํ๋ค๐
๐ต ๊ณต์๋ฌธ์
filter(function, iterable)
Construct an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.
Note that filter(function, iterable) is equivalent to the generator expression (item for item in iterable if function(item)) if function is not None and (item for item in iterable if item) if function is None.
See itertools.filterfalse() for the complementary function that returns elements of iterable for which function returns false.
Built-in Functions — Python 3.8.5 documentation
Built-in Functions The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order. abs(x) Return the absolute value of a number. The argument may be an integer or a floating po
docs.python.org