Вопрос

I want to use arguments that are passed to my function as **kwargs like a filter. That is, only if the attributes of object n are == v the element should be appended to the list.

My current solution looks like this. Is there better way to do this? Looks pretty hacky to me.

def filter_nodes(self, **kwargs):
    r = []
    for n in self.pcode:
        for k,v in kwargs.iteritems():
            if getattr(n,k) == v:
                sign  = True
            else:
                sign = False
        if sign is True:
            r.append(n)
    return r

Update

This is what the function now looks like. Thanks for all the useful comments.

def filter_nodes(self, **kwargs):
    bib = {'eq': '==','gt': '>','st': '<','geqt': '>=','seqt': '<=', 'neq':'!=' } 
    r = [] 
    for n in d:
        if all(eval('%s%s%s' % (getattr(n,k),bib[v[1]], v[0])) for k,v in kwargs.iteritems()):
            r.append(n)
     return r
Это было полезно?

Решение

I believe this will have the same functionality:

def filter_nodes(self, **kwargs):
    return [n for n in self.pcode 
            if all(getattr(n, k) == v for k, v in kwargs.iteritems())]

UPDATE: actually, it won't, it will require all the attributes to be equal with the values found in kwargs, whereas in your snippet, the last key/value pair of kwargs will decide if n can be added or not. perhaps you should specify in which exact conditions it is allowed to be added.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top