Why was Python's filter
designed such that if you run filter(my_predicate, some_set)
, I get back a list
object return than a set
object?
Are there practical cases where you would not want the result to be a set
...?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
You can do a set comprehension.
such as
Many of the "functional" functions in Python 2 are standardized on having
list
as the output type. This was just an API choice long ago. Initertools
many of the same "functional" functions standardize on providing a generator from which you could populate whatever data structure you'd like. And in Python 3 they are standardized on providing an iterator.But do also note that "filtering" in Python is not like it is in some other languages, like, say Haskell. It's not considered to be a transformation within the context of the data structure, and you don't choose to "endow" your data structures with "filterability" by making them an instance of Functor (or whatever other similar ideas exist in other languages).
As a result, it's a common use case in Python to say something like: "Here's a set, but I just want back all of the values less than 5. I don't care about their 'set-ness' after that point cause I'm just going to do some other work on them, so just give me a ____." No need to get all crazy about preserving the context within which the values originally lived.
In a dynamic typing culture this is very reasonable. But in a static typing culture where preserving the type during transformations might matter, this would be a bit frustrating. It's really just sort of a heuristic from Python's particular perspective.
If it was really just in a very narrow context of a
set
ortuple
then I might just write a helper function:such as
which works in both Python 2.10 and Python 3.4. In Python 2 this feels a bit wasteful; constructing from the iterator in Python 3 is better.
This is not limited to
filter()
. But the API has changed in Python 3, wherefilter()
now returns an iterator instead of a list. Quoting the python documentation:This article written by the author of Python goes into detail for reasons for dropping
filter()
in Python 3 (but this did not happen as you can see above, although the reasoning is still important.)