Python 3 Filter - Bug Or Feature?
Okay, I am a complete newbie to Python - and stackoverflow. I am coming from a ksh and Perl background. The following in an interactive session with Python 2.7: Python 2.7.3
Solution 1:
As per the documentation, filter
in Python 3.x returns an iterator, rather than a list as in version 2.x. This is more memory-efficient than generating the whole list up-front. If you want the list back, you can wrap the iterator in a list()
call:
VALIDVALUES = list(filter(...))
Alternatively, and as recommended by What’s New In Python 3.0, you could rewrite it as a list comprehension without a lambda
:
VALIDVALUES = [x for x in [...] if re.search(r'^' + KEY + '\=', x)]
Solution 2:
Note that you don't usually need a list of values. You can directly loop the output like below
for value in VALIDVALUES:
do_some_thing(value)
or
for value in filter(...):
do_some_thing(value)
Sometimes you may need unique values or non mutable values. Use set
or tuple
or frozenset
instead of list
as shown in the other answer.
Post a Comment for "Python 3 Filter - Bug Or Feature?"