繁体   English   中英

我如何将一组代码合并到此Python代码中,以便它可以像已经执行的一样工作

[英]how do i incorporate a set into this Python code so it can work the same way as it does already

此代码输入数字列表,仅输出列表中具有正号和负号的数字。 因此,例如,它输入列表(2,3,4,-2,-3),而输出为(2,3,-2,-3)。

此功能确实有效,但是我正在寻找如何使此功能输出一个set ,以确保没有重复。

def pos_neg(a):
  return [i for i in a if -i in a]

总结两个评论,您可以将括号替换为大括号:

def pos_neg(a):
    return {i for i in a if -i in a}

或者,为了更快地处理长列表,请执行以下操作:

def pos_neg(a):
    return {-i for i in a}.intersection(a)

或者,如果您想再次返回列表:

def pos_neg(a):
    return list({-i for i in a}.intersection(a))

但是,返回的列表将不被排序。 如果要返回有序列表(按大小):

def pos_neg(a):
    return sorted({-i for i in a}.intersection(a))

如果要返回保留原始顺序的列表,请执行以下操作:

from collections import OrderedDict

def pos_neg(a):
    s = set(a)
    return list(OrderedDict.fromkeys(i for i in a if -i in s))

或者,如果您不想使用OrderedDict:

def pos_neg(a):
    s = set(a)
    t = set()
    b = []
    for i in a:
        if -i in s and i not in t:
            t.add(i)
            b.append(i)
    return b

或者,如果您想使用列表理解:

def pos_neg(a):
    s = set(a)
    t = set()
    return [i for i in a if -i in s and not (i in t or t.add(i))]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM