我已经弄清楚了接受一个列表并返回一个列表的代码,其中每个元素只出现一次。但我无法弄清楚我需要做什么才能消除没有负数的数字:
例如如果一个列表有数字 [1,-1,2,-2,3]。返回列表时,它将删除 3。
目前为止
def one(a):
conversion = set()
conversion_add = conversion.add
elim = [x for x in a if x not in conversion and not conversion_add(x)]
接下来我需要做什么? If 语句,我需要使用什么语法来比较正数和负数,以便我可以删除多余的数字而没有负数?
非常感谢
最佳答案
听起来不错:
src = set([1,-1,2,-2,3])
no_match = set(a for a in src if -a not in src)
match = set(a for a in src if -a in src)
结果:
>>> src = set([1,-1,2,-2,3])
>>> no_match = set(a for a in src if -a not in src)
>>> match = set(a for a in src if -a in src)
>>> no_match
set([3])
>>> match
set([1, 2, -1, -2])
关于Python:如果集合中没有负计数器部分,则删除集合中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19339627/