Python 不使用set()删除元组中的重复项

Python 不使用set()删除元组中的重复项,python,set,duplicates,tuples,Python,Set,Duplicates,Tuples,我得到的是一个错误而不是正确答案(1,-13,8,5,0,4,-1,-4)。 我的错误是什么 x = (1,1,-13,8,5,0,4,-1,-4) a = filter(lambda i,j: i == j, x) print(tuple(a)) 输出: x = (1,1,-13,8,5,0,4,-1,-4) seen = [] answer = [] for elem in x: if elem not in seen: seen.append(elem)

我得到的是一个错误而不是正确答案
(1,-13,8,5,0,4,-1,-4)
。 我的错误是什么

x = (1,1,-13,8,5,0,4,-1,-4)

a = filter(lambda i,j: i == j, x)

print(tuple(a))
输出:

x = (1,1,-13,8,5,0,4,-1,-4)
seen = []
answer = []
for elem in x:
    if elem not in seen:
        seen.append(elem)
        answer.append(elem)
print(tuple(answer))

filter
将迭代
x
,并将每个元素传递给lamdba函数。但是,它一次只传递一个元素。因此,lambda函数不能接受两个元素(除非最后一个元素具有默认值)

除此之外,还有很多解决方案不使用
set
。例如,您可以使用
collections.OrderedDict
,如下所示

(1, -13, 8, 5, 0, 4, -1, -4)
x = (1, 1, -13, 8, 5, 0, 4, -1, -4)
from collections import OrderedDict
print tuple(OrderedDict.fromkeys(x))
# (1, -13, 8, 5, 0, 4, -1, -4)
print tuple({}.fromkeys(x))
# (0, 1, 4, 5, 8, -13, -4, -1)
如果元素的顺序无关紧要,您可以使用普通字典本身,如下所示

(1, -13, 8, 5, 0, 4, -1, -4)
x = (1, 1, -13, 8, 5, 0, 4, -1, -4)
from collections import OrderedDict
print tuple(OrderedDict.fromkeys(x))
# (1, -13, 8, 5, 0, 4, -1, -4)
print tuple({}.fromkeys(x))
# (0, 1, 4, 5, 8, -13, -4, -1)
或者您可以使用一个临时的
seed
列表,如下所示

(1, -13, 8, 5, 0, 4, -1, -4)
x = (1, 1, -13, 8, 5, 0, 4, -1, -4)
from collections import OrderedDict
print tuple(OrderedDict.fromkeys(x))
# (1, -13, 8, 5, 0, 4, -1, -4)
print tuple({}.fromkeys(x))
# (0, 1, 4, 5, 8, -13, -4, -1)

假设您可能在列表中的任何位置都有重复项,而不仅仅是连续的重复项,过滤器对您没有多大帮助

您可以通过自定义功能使用
reduce

x = (1, 1, -13, 8, 5, 0, 4, -1, -4)
seen, result = [], tuple()
for item in x:
    if item not in seen:
        seen.append(item)
        result += (item, )
print result
# (1, -13, 8, 5, 0, 4, -1, -4)
此外,如果您只想删除连续的重复,也很容易:

reduce(lambda acc, e: acc if e in acc else acc + (e, ), x, ())
或手工编写的代码

reduce(lambda acc, e: acc if e in acc[-1:] else acc + (e, ), x, ())
下面是几个使用
过滤器的答案,仅供参考:

rv = []
for i in x:
    if i not in rv:  # any repetition
    if i not in rv[-1:]  # only successive repetitions
        rv.append(i)
result = tuple(rv)
输出:

x = (1, 1, -13, 8, 5, 0, 4, -1, -4)

print(tuple([item for index, item in enumerate(x) if item not in x[:index]]))

filter
callable只能传递一个参数;是什么让你认为它会通过两次?为什么任意限制一个集合不能被使用?你的实际目标是什么?@MartijnPieters——是的,对我来说感觉像是一个……没有任何关于你实际需要什么的进一步反馈,我假设你想在保持秩序的同时删除重复项。可能的重复项