I tried many different examples for filter()
with anonymous functions, but always get strange results as long as I use it on strings. Below is an example:
>>>print(filter(lambda x: x.isdigit(), "aas30dsa20"))
<filter object at 0x00000000035DE470>
If not strings, everything works fine. Eg;
>>> print(list(filter(lambda x: x >= 30 and x <= 70, [x**2 for x in range(1,11)])))
[36, 49, 64]
By the way, if I remove the list()
function part, the problem similar to string case appears:
>>> print(filter(lambda x: x >= 30 and x <= 70, [x**2 for x in range(1,11)]))
<filter object at 0x00000000037BFDD8>
I am using Python 3.4.1 on Windows 7.
Yes. Several functional tools (most notably filter()
and map()
) were changed to return iterators instead of sequences for 3.x.
In Python 2, the filter() function returned a list, the result of filtering a sequence through a function that returned True or False for each item in the sequence. In Python 3, the filter() function returns an iterator, not a list. Source: diveintopython3.net
2to3 tool will in some cases place a list() call around the call to filter() to ensure that the result is still a list. If you need code that runs in both Python 2 and Python 3 without 2to3 conversion and you need the result to be a list, you can do the same.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.