(新手问题)我想编写一个 Python 程序,如果它存在于集合中,则从集合中删除它。
预定义集合后,代码如下所示:
set = {1,2,3,4,4,5,6,10}
set.discard(4)
print(set)
写这个的方法是什么,以便它适用于任何事先未知的值集?我尝试了以下但没有奏效。有没有一种方法可以做到这一点?
def set(items):
if i in items == 4:
set.discard(4)
else:
print("The number 4 is not in the set.")
print(set({1,2,4,6}))
这将丢弃4
传递给函数的任何集合中的 :
def discard4(items):
if 4 in items:
items.discard(4)
return "Discarded"
else:
return "The number 4 is not in the set."
print(discard4({1,2,6})) # will print "The number 4 is not in the set."
print(discard4({1,2,4,6})) # will print "Discarded"
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句