使用函数从集合中删除具体值

时间:2018-11-16 23:13:28

标签: python

(新手问题)我想编写一个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}))

1 个答案:

答案 0 :(得分:2)

这将丢弃传递给函数的任何集合中的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"