You are here: > Dive Into Python > Functional Programming > Filtering lists revisited | << >> | ||||
Dive Into PythonPython from novice to pro |
You're already familiar with using list comprehensions to filter lists. There is another way to accomplish this same thing, which some people feel is more expressive.
Python has a built-in filter function which takes two arguments, a function and a list, and returns a list.[7] The function passed as the first argument to filter must itself take one argument, and the list that filter returns will contain all the elements from the list passed to filter for which the function passed to filter returns true.
Got all that? It's not as difficult as it sounds.
>>> def odd(n):... return n % 2 ... >>> li = [1, 2, 3, 5, 9, 10, 256, -3] >>> filter(odd, li)
[1, 3, 5, 9, -3] >>> [e for e in li if odd(e)]
>>> filteredList = [] >>> for n in li:
... if odd(n): ... filteredList.append(n) ... >>> filteredList [1, 3, 5, 9, -3]
files = os.listdir(path)test = re.compile("test\.py$", re.IGNORECASE)
files = filter(test.search, files)
Historical note. Versions of Python prior to 2.0 did not have list comprehensions, so you couldn't filter using list comprehensions; the filter function was the only game in town. Even with the introduction of list comprehensions in 2.0, some people still prefer the old-style filter (and its companion function, map, which you'll see later in this chapter). Both techniques work at the moment, so which one you use is a matter of style. There is discussion that map and filter might be deprecated in a future version of Python, but no decision has been made.
files = os.listdir(path) test = re.compile("test\.py$", re.IGNORECASE) files = [f for f in files if test.search(f)]
[7] Technically, the second argument to filter can be any sequence, including lists, tuples, and custom classes that act like lists by defining the __getitem__ special method. If possible, filter will return the same datatype as you give it, so filtering a list returns a list, but filtering a tuple returns a tuple.
<< Finding the path | | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | | Mapping lists revisited >> |