繁体   English   中英

您如何更改集合中的特定元素?

[英]How do you change a specific element of a set?

在这段代码中,我试图将每次循环的集合的值与参数中传递的值(在本例中为a)进行比较。 但是有趣的是,它显示了当我为每个循环使用a时,每个元素都是整数。 如何获得没有控制台错误的整数到整数比较?

def remove(s,a,b):
    c=set()
    c=s
    for element in c:
        element=int(element)
        if(element<a or element>b):
            c.discard(element)
    return c

def main():
    remove({3, 17, -1, 4, 9, 2, 14}, 1, 10)

main()

输出:

    if(element<=a or element>=b):
TypeError: '>=' not supported between instances of 'int' and 'set'

您重新分配本地变量b

def remove(s,a,b):
    b=set()  # now b is no longer the b you pass in, but an empty set
    b=s  # now it is the set s that you passed as an argument
    # ...    
    if(... element > b): # so the comparison must fail: int > set ??

使用集合理解的简短实现:

def remove(s, a, b):
    return {x for x in s if a <= x <= b}

>>> remove({3, 17, -1, 4, 9, 2, 14}, 1, 10)
{9, 2, 3, 4}

如果要int进行int比较,则将b作为s的列表。

def remove(s,a,b):
    b = list(s)
    for element in s:
        element=int(element)      
        if(element< a or element > b):
            b.remove(element)
    return b

def main():
    remove({3, 17, -1, 4, 9, 2, 14}, 1, 10)

main()

来吧,为什么我们不缩短代码呢?

尝试这个:

def remove(s, a, b):
    return s.difference(filter(lambda x: not int(a) < int(x) < int(b), s))


def main():
    new_set = remove({3, 17, -1, 4, 9, 2, 14}, 1, 10)

    # {2, 3, 4, 9}
    print(new_set)


main()

暂无
暂无

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

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