Python中的递归列表理解? [英] Recursive list comprehension in Python?

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

问题描述

是否可以在Python中定义递归列表理解?

Is it possible to define a recursive list comprehension in Python?

可能是一个简单的示例,但类似以下内容:

Possibly a simplistic example, but something along the lines of:

nums = [1, 1, 2, 2, 3, 3, 4, 4]
willThisWork = [x for x in nums if x not in self] # self being the current comprehension

像这样可能吗?

推荐答案

不,没有(记录的,可靠的,稳定的,... ;-)引用当前理解"的方法.您可以使用循环:

No, there's no (documented, solid, stable, ...;-) way to refer to "the current comprehension". You could just use a loop:

res = []
for x in nums:
  if x not in res:
    res.append(x)

当然这是非常昂贵的(O(N平方)),所以您可以使用辅助set对其进行优化(我假设保持res中的项目顺序与nums,否则set(nums)会帮助您;-)...:

of course this is very costly (O(N squared)), so you can optimize it with an auxiliary set (I'm assuming that keeping the order of items in res congruent to that of the items in nums, otherwise set(nums) would do you;-)...:

res = []
aux = set()
for x in nums:
  if x not in aux:
    res.append(x)
    aux.add(x)

对于非常长的列表(O(N)而不是N平方),这要快得多.

this is enormously faster for very long lists (O(N) instead of N squared).

编辑:在Python 2.5或2.6中,vars()['_[1]']实际上可能以您想要的self角色(对于非嵌套listcomp)工作...这就是为什么我要限定我的通过澄清没有声明来提供可靠,稳定,稳定的方式来访问正在建立的列表"的声明-独特的,没有记录的名称" '_[1]'(故意选择不是有效的标识符;- )是实现工件"的最高点,任何依赖它的代码都应摆脱痛苦;-).

Edit: in Python 2.5 or 2.6, vars()['_[1]'] might actually work in the role you want for self (for a non-nested listcomp)... which is why I qualified my statement by clarifying there's no documented, solid, stable way to access "the list being built up" -- that peculiar, undocumented "name" '_[1]' (deliberately chosen not to be a valid identifier;-) is the apex of "implementation artifacts" and any code relying on it deserves to be put out of its misery;-).

这篇关于Python中的递归列表理解?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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