如何在保留订单的同时从字符串中删除单个数字

时间:2014-10-16 14:00:11

标签: python string duplicates

def pos_and_neg(a):
    seen = set()
    seen_add = seen.add
    return [ x for x in a if not (x in seen or seen_add(x))] 

print pos_and_neg([1,2,3,-1,-3])

这需要返回

[1,3,-1,-3]

2 个答案:

答案 0 :(得分:0)

 def pos_and_neg(a):
    return [ x for x in a if (x*(-1)) in a] 
 print pos_and_neg([1, 4, 6, -1, -4, -6, 5, 7, -7])

输出: - [1, 4, 6, -1, -4, -6, 7, -7]

答案 1 :(得分:0)

你可以做这样的事情

def pos_and_neg(l):
    unique = set(l)  # use a set for faster lookups
    return [i for i in l if (i*-1) in unique]

>>> pos_and_neg([1,4,5,6,-1,2,-4,-6])
[1, 4, 6, -1, -4, -6]

虽然它不会处理重复项,但如果您有[1,1,-1],则会保留所有值,而不是删除其中一个1