递归的词典理解

时间:2013-08-07 23:57:51

标签: python functional-programming

我正在使用一些非常规代码构建一个复杂的字典。我只是好奇是否有一些方法来检查当前字典的值,甚至是当前列表的值,同时构建它以避免重复/不需要的值。这是我的代码:

locations = {words[i]: map(lambda x: words[x::].index(words[i]) if words[i] in words[x::] and words[x::].index(words[i]) not in self[words[i]] else None, range(len(words))) for i in range(len(words))}

# the important part here is 

and words[x::].index(words[i]) not in self[words[i]]

在没有for / while迭代的情况下,是否可以使用上述内容?

1 个答案:

答案 0 :(得分:4)

我强烈怀疑你是否可以通过理解来访问实际构建的列表,因为到目前为止它还不存在。

尽管如此,这并不意味着您无法以功能方式构建删除重复项的列表。 (请记住,python不允许TCO。)

如果我们想要从另一个列表构建列表,只使用列表而不是集合,有序集合等,一种方法可能是(中途功能样式):

def removeDuplicates (inList, acc):
    if not inList: return acc
    if inList [0] in acc: return removeDuplicates (inList [1:], acc)
    return removeDuplicates (inList [1:], acc + [inList [0] ] )
    #even tail-recursive, although this doesn't help in python

print (removeDuplicates ( [1,2,3,2,3,5,1], [] ) )

作品。所以让我们用它构建一个lambda表达式:

rd = lambda inList, acc: acc if not inList else rd (inList [1:], acc + ( [] if inList [0] in acc else [inList [0] ] ) )

print (rd ( [1,2,3,2,3,5,1], [] ) )

也适用。现在让我们准备这个lambda用于匿名和递归:

rd2 = lambda f, inList, acc: acc if not inList else f (f, inList [1:], acc + ( [] if inList [0] in acc else [inList [0] ] ) )

rec = lambda f, *a: f (f, *a)

print (rec (rd2, [1,2,3,2,3,5,1], [] ) )

仍然有效。现在让我们删除lambdas的名称,我们得到了一个递归的lambda,它可以在删除重复项的同时从另一个列表构建列表(没有for或其他命令式循环):

print ( (lambda f, *a: f (f, *a) ) (lambda f, inList, acc: acc if not inList else f (f, inList [1:], acc + ( [] if inList [0] in acc else [inList [0] ] ) ), [1,2,3,2,3,5,1], [] ) )

不完全可读,但功能和递归。

如果您正在进行函数式编程,lambda f, *a: f (f, *a)肯定会成为您的密友。

inb4 import this和PEP8。