从对象列表中找出特定属性

时间:2019-07-08 17:53:10

标签: python-3.x

我想将对象列表中每个对象的属性作为参数传递给函数。

我知道我可以使用*list传递对象本身。我想知道是否有一种方便的方法可以通过(*list).attribute之类的对象传递某个属性。

class Cls():
  def __init__(self, value = 0):
    self.value = value

def func(arg1, arg2, arg3):
  # do something with args
  print(arg1, arg2, arg3)

cls1 = Cls(1)
cls2 = Cls(2)
cls3 = Cls(3)

clsList = [cls1, cls2, cls3]

# is there something short like this?
func((*clsList).value)

# I know I could do something like this
func(*[c.value for c in clsList])
# but I was wondering if there was a way to avoid having the intermediate list

2 个答案:

答案 0 :(得分:0)

是的,您可以使用生成器表达式来避免中间列表:

func(*(c.value for c in clsList))

请注意,[x for x in 'abc']是一个列表,将立即对其求值,而(x for x in 'abc')(带有括号而不是括号)是一个生成器, 在以下位置不被完全求值定义,因此将只创建一个小的中间对象,而不是一个可能很大的列表。

答案 1 :(得分:0)

您可以使用operator.attrgetter

import operator
func(*map(operator.attrgetter('value'), clsList))

f = operator.attrgetter('value')之后,呼叫f(c)返回c.valuemapf应用于clsList中的每个项目,然后func(*map(...))将解压后的映射值作为参数传递给func