[英]Python - Removing duplicates in list only by using filter and lambda
I need to remove duplicates in a list without set, functions or loops - only by using filter and a lambda function.我需要在没有集合、函数或循环的情况下删除列表中的重复项 - 仅通过使用过滤器和 lambda 函数。
My attempt was:我的尝试是:
list(filter(lambda x: x in l[:].remove(x), l))
But remove returns the removed item and not the whole list.但是 remove 返回已删除的项目而不是整个列表。 Any suggestions?
有什么建议?
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) is None and 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.如果你有
l = [1, 2, 2, 3, 2]
,你最终会得到[1, 3, 2]
作为结果列表。
Or create an empty list and use it to keep track of what you've seen:或者创建一个空列表并使用它来跟踪您所看到的内容:
seen = []
return filter(lambda x: seen.append(x) is None if x not in seen else False, 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). :-) 并且两者都使用愚蠢的机制来允许在适当的位置改变列表但返回 True/False 结果(它们中的
is None
部分允许我们将表达式链接在一起)。
If you can use map
and enumerate
, you could do something like:如果您可以使用
map
和enumerate
,您可以执行以下操作:
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
:如果您可以使用列表推导式,则可以删除
map
的使用:
[x for i, x in filter(lambda t: l[:t[0]].count(t[1]) == 0,
enumerate(l))]
If you could use reduce
, then you could do something like:如果您可以使用
reduce
,那么您可以执行以下操作:
reduce(lambda r, x: r + [x] if x not in 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.不过,这些都不是我所说的优雅的 Python 代码,除了可能是
reduce
版本——尽管它的性能不高。
I made a solution using only a lambda
function.我只使用
lambda
函数做了一个解决方案。
The following lambda
function returns a list corresponding to the list passed as argument, without duplicates:以下
lambda
函数返回与作为参数传递的列表相对应的列表,没有重复项:
lambda l: (lambda u, a: u(u, a)) ((lambda f, x: x if len(x) <= 1 else (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 .由于目标有点不同,我发布了一个单独的问答,在那里我解释了这一点: 仅使用 lambda 函数删除重复项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.