Filter object error in Python 3

前端 未结 1 1607
悲&欢浪女
悲&欢浪女 2021-01-19 00:41

When I run this code in Python 3:

languages = [\"HTML\", \"JavaScript\", \"Python\", \"Ruby\"]
print( filter(lambda x: x == \"Python\",languages))

相关标签:
1条回答
  • 2021-01-19 01:24

    It is not an error - you printed an object of type filter as the filter() don't return list - it constructs an iterator, but only if there is a request for it.

    The simplest solution is to use the function list() - it requests an iterator and returns the list:

    print( list(filter(lambda x: x == "Python", languages)))
    

    instead of your command

    print( filter(lambda x: x == "Python",languages))
    

    Note: It is similar to printing range(10) (which is an object) and printing list(range(10)) (which is the list).

    There are changes between Python 2.x and Python 3.x in almost all functions which returned a list in Python 2.x - in Python 3.x they return something more general and less memory consuming, something as recipe how to obtain elements in the case of interest.

    Compare: 1, 2, 3, 4, 5, 6, 7, 8, 9 and integers from 1 to 9 (or 1, 2, ..., 9).
    No difference? Try write down all integers from 1 to 999999.

    0 讨论(0)
提交回复
热议问题