如何使用列表理解来上链列表? [英] How to walk up a linked-list using a list comprehension?

查看:42
本文介绍了如何使用列表理解来上链列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用列表表达式遍历分层结构(如链表)的方法,但是还没有提出任何可行的方法.

I've been trying to think of a way to traverse a hierarchical structure, like a linked list, using a list expression, but haven't come up with anything that seems to work.

基本上,我想转换以下代码:

Basically, I want to convert this code:

p = self.parent
names = []
while p:
  names.append(p.name)
  p = p.parent
print ".".join(names)

变成单线,如:

print ".".join( [o.name for o in <???>] )

我不确定如何在???部分进行遍历,尽管以通用方式(如果可能的话).我有几种具有类似.parent type属性的结构,并且不想为每个结构编写一个yielding函数.

I'm not sure how to do the traversal in the ??? part, though, in a generic way (if its even possible). I have several structures with similar .parent type attributes, and don't want to have write a yielding function for each.

我不能使用对象本身的__iter__方法,因为它已经用于迭代对象本身包含的值.除了liori的答案外,大多数其他答案都对属性名称进行了硬编码,这是我要避免的.

I can't use the __iter__ methods of the object itself because its already used for iterating over the values contained within the object itself. Most other answers, except for liori's, hardcode the attribute name, which is what I want to avoid.

这是我根据liori的回答改编的内容:

Here's my adaptation based upon liori's answer:

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)

推荐答案

如果您希望您的解决方案具有通用性,请使用通用技术.这是一个类似于生成器的定点:

If you want your solution to be general, use a general techique. This is a fixed-point like generator:

def fixedpoint(f, start, stop):
    while start != stop:
        yield start
        start = f(start)

只要这两个值都不等于stop,它将返回产生收益的发电机f(start),f(f(start)),f(f(f(start))),....

It will return a generator yielding start, f(start), f(f(start)), f(f(f(start))), ..., as long as neither of these values are equal to stop.

用法:

print ".".join(x.name for x in fixedpoint(lambda p:p.parent, self, None))

多年以来,我的个人助手库具有类似定点的功能...对于快速黑客攻击来说非常有用.

My personal helpers library has similar fixedpoint-like function for years... it is pretty useful for quick hacks.

这篇关于如何使用列表理解来上链列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆