social_loser
social_loser

Reputation: 153

pythonic way to filter a list derived class?

Here is the pseudo code:

class Foo (list):
    def methods...

foo=Foo()
foo.readin()

rule='....'
bar=[for x in foo if x.match(rule)]

Here, bar is of a list, however I'd like it to be a instance of Foo, The only way I know is to create a for loop and append items one by one:

bar=Foo()

for item in foo:
    if item.match(rule):
        bar.append(item)

So I'd like to know if there is any more concise way or more pythonic way to do this ?

Upvotes: 1

Views: 216

Answers (2)

social_loser
social_loser

Reputation: 153

It seems another answer got deleted because the original answerer deleted it. So I post the other way here for completeness. If the origin answerer restore he's answer I will delete this answer myself.

another way to do this is to use the build in filter function. the code is :

bar=filter( lambda x: x.match(rule) , foo )

I guess why the original answer guy deleted his answer because it is said to be a not encouraged using the filter function. I have done some research before asked this question. But I think I learned a lot from that answer. Because I have tried to use the filter function myself , but never figured out how to use it correctly. So this answer taught me how to read the manual Correctly, and no matter what, it is still a valid way to solve my problem. So here, if the original answerer can see my post, thank you I appreciate your help and it surely helped me.

updated: as what said by Martijn in the comment, this is not a valid answer. I'll keep this anwser because this talk is good. but this is not a valid way to solve my problem.

Upvotes: -1

Martijn Pieters
Martijn Pieters

Reputation: 1123400

You can pass in a generator expression to the Foo() call:

bar = Foo(x for x in foo if x.match(rule))

(When passing a generator expression to a call, where it is the only argument, you can drop the parentheses you normally would put around a generator expression).

Upvotes: 4

Related Questions