首页 > 解决方案 > Is there a way to iterate over a specific object's attribute of in a for loop?

问题描述

Is there any clean way to get a list item's field in a for loop, i.e. directly iterating over the field values without explicitly getting it in the loop itself. Example:

from collections import namedtuple

Person = namedtuple("Person", ["name", "age"])
p1 = Person("Bob", 42)
p2 = Person("Sam", 19)
l = [p1, p2]
for p in l:
    p_name = p.name
    print(p_name)

I would like to get the parameter p_name from the for declaration. The use of tuples is only for example, the solution should work also for objects and preferably for dict

标签: python

解决方案


由于您使用的是命名元组,它仍然只是一个元组 - 您可以使用元组解包-

for p_name, _ in l:
    print(p_name)

编辑:只是为了在这个答案中说清楚 - 目前没有办法在for循环的 init 部分直接进行对象解构/解包。唯一支持的解包结构是元组解包。

对于有序对象,您可以使用dir(或特定于对象的其他方法/函数)获取所有值的元组(实际上是一个列表),并对它们使用元组解包。

但是,您可以将其作为一个多步骤过程来处理 - 通过将仅提取您想要的字段的函数映射到可迭代的元组中 - 然后遍历结果并使用元组解包。使用惰性生成器有效地做到这一点。这是@Andreas 在评论中提到的技术,即-

for p_name in (p.name for p in l):
  print(p_name)

你可以对任何对象做同样的事情——

for pfoo, pbar, pbaz in ((p.foo, p.bar, p.baz) for p in l):
  print(pfoo, pbar, pbaz)

推荐阅读