Reputation: 1992
I am building out a complex dictionary with some unconventional code. I'm just curious if there is some way to check the current dictionary's value or even the current list's values while building it out as to avoid duplicates/unwanted values. Here is the code I have:
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]]
Is anything like the above possible without for/while iteration?
Upvotes: 2
Views: 581
Reputation: 32459
I strongly doubt that you can access the list actually being built with a comprehension, as it doesn't exist so far.
Nevertheless, this doesn't mean that you cannot build a list removing duplicates in a functional manner. (Just keep in mind that python doesn't allow for TCO.)
If we want to build a list from another list, just using lists and not sets, ordered sets or the like, one way could be (half-way functional style):
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], [] ) )
Works. So let's build a lambda-expression out of it:
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], [] ) )
Works, too. Now let's prepare this lambda for anonymity and recursion:
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], [] ) )
Still works. Now let's remove the name for the lambdas and we got a recursive lambda that builds a list from another while removing duplicates (without for
or other imperative loops):
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], [] ) )
Not exactly readable, but functional and recursive.
If you are into functional programming, lambda f, *a: f (f, *a)
sure will be a close friend of yours.
inb4 import this
and PEP8.
Upvotes: 4