【问题标题】:How do you change a specific element of a set?如何更改集合的特定元素?
【发布时间】:2017-12-01 06:25:06
【问题描述】:

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

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 = s 并且 s 是 Set 。你不能将 int 与 Set 进行比较

标签: python types integer set comparison


【解决方案1】:

你重新分配你的局部变量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}

【讨论】:

  • 所以你把参数b变成了一个集合?并比较设置为设置?
  • 不,sn-p 来自您的代码;)您将b 设为一个集合,然后将该集合与集合的(整数)元素进行比较。
【解决方案2】:

如果你想让 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()

【讨论】:

    【解决方案3】:

    来吧,我们为什么不把代码缩短一点?

    试试这个:

    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()
    

    【讨论】:

      猜你喜欢
      • 2012-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多