在这段代码中,我试图将每次循环的集合的值与参数中传递的值(在本例中为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'
答案 0 :(得分:2)
您重新分配本地变量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}
答案 1 :(得分:0)
如果你想要int to int compare,那么把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()
答案 2 :(得分:0)
来吧,我们为什么不缩短代码?
试试这个:
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()