Python:如果集合中没有负计数器部分,则删除集合中的数字

标签 python syntax numbers set

我已经弄清楚了接受一个列表并返回一个列表的代码,其中每个元素只出现一次。但我无法弄清楚我需要做什么才能消除没有负数的数字:

例如如果一个列表有数字 [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/

相关文章:

python - 删除重复的列表元素

python - 如何在 Pandas 中打印 float ?

c++ - 在 C++ 函数中定义的对象在超出范围后是否会被销毁?

python - 使用 paramiko 进行远程端口转发

python - NLTK - 多标签分类

javascript - 如何在 firebug 命令中选择 div id?

syntax - 如何在精益中使用求和符号?

Haskell:两个整数列表之间的匹配次数?

python - 我如何使用正则表达式判断一个字符串是否仅包含 python 中的数字和空格

binary - 负数如何用32位带符号整数表示?