Python - Removing Duplicates In List Only By Using Filter And Lambda
Solution 1:
You need to keep some state somehow. If you can use a new list, you could do something like this:
g = l[:]
filter(lambda x: g.remove(x) isNoneand g.count(x) == 0, l)
The above removes duplicates differently. If you had l = [1, 2, 2, 3, 2]
, you'd end up with [1, 3, 2]
as the resultant list.
Or create an empty list and use it to keep track of what you've seen:
seen = []
returnfilter(lambda x: seen.append(x) isNoneif x notin seen elseFalse, l)
Both the above is pretty akin to using sets, though far less efficient. :-) And both are using a goofy mechanism to allow mutate a list in place but return a True/False result (the is None
portion in both of them is allowing us to chain expressions together).
If you can use map
and enumerate
, you could do something like:
map(lambda t: t[1],
filter(lambda t: l[:t[0]].count(t[1]) == 0, enumerate(l)))
(it uses the current index to look into the previous part of the list to find duplicates)
If you can use list comprehensions, you could remove the use of map
:
[x for i, x infilter(lambda t: l[:t[0]].count(t[1]) == 0,
enumerate(l))]
If you could use reduce
, then you could do something like:
reduce(lambda r, x: r + [x] if x notin r else r, l, [])
as you can keep state by passing the result from one iteration to the next.
But somehow you're going to need to have a record of what has been seen. None of this is what I'd call elegant Python code though, except maybe the reduce
version--though it's not performant.
Solution 2:
I made a solution using only a lambda
function.
The following lambda
function returns a list corresponding to the list passed as argument, without duplicates:
lambda l: (lambda u, a: u(u, a)) ((lambda f, x: x iflen(x) <= 1else (f(f, x[1:]) if x[0] in x[1:] else ([x[0]] + f(f, x[1:])))), l)
Since the target is a bit different, I posted a separate Q/A, where I explain this: Removing duplicates using only lambda functions.
Post a Comment for "Python - Removing Duplicates In List Only By Using Filter And Lambda"