一千萬個為什麽

搜索

Python中的遞歸列表理解?

是否可以在Python中定義遞歸列表推導?

可能是一個簡單的例子,但有些東西:

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

這樣的事情可能嗎?

最佳答案

不,沒有(記錄在案的,穩定的,穩定的,...... ;-)方式來引用“當前的理解”。你可以使用一個循環:

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

當然這是非常昂貴的(O(N平方)),所以你可以用輔助 set 來優化它(我假設保持 res 中項目的順序)與 nums 中的項目一致,否則 set(nums)會對你有所幫助; - )...:

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

對於非常長的列表(O(N)而不是N平方),這非常快。

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中的遞歸列表理解?