Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在保留顺序的同时从字符串中删除单个数字_Python_String_Duplicates - Fatal编程技术网

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

Python 如何在保留顺序的同时从字符串中删除单个数字,python,string,duplicates,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,4,6,-1,-4,-6,7,-7]您可以这样做 def pos_and_neg(a): return [ x for x in a if (x*(

这需要回归

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,4,6,-1,-4,-6,7,-7]

您可以这样做

 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,1,-1]
所有值都将保留,而不是删除
1
s中的一个。

您的意思是,您只想保留一个值,如果该值同时存在于正数和负数中(例如,1和-1、3和-3)?如果有重复怎么办?是的,准确地说,使它模块化到任何你通过它的打印这里没有涉及字符串…列表***对不起,不是字符串听起来不错,但它对打印pos_和_neg([1,4,5,6,-1,-4,-6])有效吗?我只是想使它模块化,这样它就可以处理你抛出的任何打印it@NickBergeron对于
[1,4,5,6,-1,-4,-6]
它有输出:-
[1,4,6,-1,-4,-6]
 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])
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]