Ric*_*eur 1 python list-comprehension
我一直试图想出一种使用列表表达式遍历层次结构的方法,比如链表,但是没有提出任何看似有用的东西.
基本上,我想转换这段代码:
p = self.parent
names = []
while p:
names.append(p.name)
p = p.parent
print ".".join(names)
Run Code Online (Sandbox Code Playgroud)
变成单线像:
print ".".join( [o.name for o in <???>] )
Run Code Online (Sandbox Code Playgroud)
但是,我不确定如何以通用的方式进行???部分遍历(如果它甚至可能).我有几个具有相似类型属性的结构,并且不希望为每个结构编写一个屈服函数..parent
编辑:
我不能使用__iter__对象本身的方法,因为它已经用于迭代对象本身包含的值.大多数其他答案,除了liori的,硬编码属性名称,这是我想要避免的.
根据liori的回答,这是我的改编:
import operator
def walk(attr, start):
if callable(attr):
getter = attr
else:
getter = operator.attrgetter(attr)
o = getter(start)
while o:
yield o
o = getter(o)
Run Code Online (Sandbox Code Playgroud)
我能想到的最接近的事情是创建一个父生成器:
# Generate a node's parents, heading towards ancestors
def gen_parents(node):
node = node.parent
while node:
yield node
node = node.parent
# Now you can do this
parents = [x.name for x in gen_parents(node)]
print '.'.join(parents)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
946 次 |
| 最近记录: |