Python从对象列表返回第一个具有class属性s的对象

2024-10-06 13:12:21 发布

您现在位置:Python中文网/ 问答频道 /正文

给定一个具有属性a和b的对象列表,我想从列表中满足给定约束的第一个对象获取属性。下面显示了一种解决方案,但对于具有许多属性的对象,这是不可取的。你知道吗

class Foo(object):
  def __init__(self):
  self.a = 0
  self.b = 1

def get_first_a(l):
  return next(val.a for val in l if val.a > 0)

def get_first_b(l):
  return next(val.b for val in l if val.b > 0)

def main():
  bar0 = Foo()
  bar1 = Foo()
  bar2 = Foo()
  bar2.a = 10
  l = [bar0, bar1, bar2]
  a = get_first_a(l)  # returns 10
  b = get_first_b(l)  # returns 1

有没有办法将对象属性传递给函数?我不希望添加枚举或使用字符串匹配,而是希望使用以下内容:

def get_first_b(l, object_attribute):
  return next(val.object_attribute for val in l if val.object_attribute != 0) 

Tags: 对象inselfforgetreturnif属性
3条回答

您可以使用getattr,但如果没有符合您条件的object\u属性,则最终会出现StopIteration错误:

def get_first(l, object_attribute, op, cond):
    return next((getattr(val, object_attribute) for val in l
                if op(getattr(val, object_attribute), cond)), None)

您可以将所需的内容传递给单个函数:

from operator import ne, gt, lt
def main():
    bar0 = Foo()
    bar1 = Foo()
    bar2 = Foo()
    bar2.a = 10
    l = [bar0, bar1, bar2]
    a = get_first(l,"a", gt, 0)  # returns 10
    b = get_first(l, "b", ne, 0)  # returns 1
    c = get_first(l, "b", lt, -1)
    print(a)
    print(b)
    print(c)

main()

输出:

10
1
None

使用getattr为任何属性定义一个函数

def get_first(l,attr):
  return next(getattr(val,attr) for val in l if getattr(val,attr) > 0)

如果您知道对象中的属性,请尝试以下操作:

# some class with properties
class Foo:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def retA(self):
        return self.a

    def retB(self):
        return self.b

# forming a list with the objects
l_b = []
l_b.append(Foo('a1','b1'))
l_b.append(Foo('a2','b2'))
l_b.append(Foo('a3','b3'))

# function to grab a property from object in list on the exact position in the list        
def getPropFormListOfObj(list_obj, position_in_list, property_obj):
"""
list_obj (type = list)- list of objects
position_in_list (type = int) - position of object in the list from 0 to (len(list_obj) - 1)
property_obj (type = str) - the property we want to return. in this implementation works only if == 'a' or 'b'
"""
    if (property_obj == 'a'):
        return list_obj[position_in_list].retA()
    elif (property_obj == 'b'):
        return list_obj[position_in_list].retB()        

# test
# expected output "a1"
print getPropFormListOfObj(l_b, 0, 'a')

# test
# expected output "b2"
print getPropFormListOfObj(l_b, 2, 'b')

相关问题 更多 >