python - 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
解决方案
由于您使用的是命名元组,它仍然只是一个元组 - 您可以使用元组解包-
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)
推荐阅读
- c# - c#事件的正确实现方式是什么
- r - R - 在具有平均值的区间内生成值
- python-3.x - 目录存在时不是有效的目录错误
- sdn - 如何将openflow更新到1.3
- eslint - 使用 Eslint 时真的需要 Prettier 吗?
- kubernetes - 为什么 GKE Kubernetes 集群需要一个版本?
- c# - 如何通过wcf服务更新宿主项目中的winform控件?
- windows - ContainerContentChanging 事件和数据模型更改
- c++ - 注册对对象工厂的调用会导致段错误
- angular - 如何在Angular的http GET请求中传递多个参数?