This question already has answers here:
What is difference between Discard() and Remove() function in python 3 sets [duplicate]
                                
                                    (2个答案)
                                
                        
                                在8个月前关闭。
            
                    
.discard(x):此操作从集合中删除元素。
如果element不存在,则不会引发KeyError。

.remove(x):此操作从集合中删除元素。
如果element不存在,则引发KeyError。

所以我的问题是,使用remove(x)函数的原因在哪里,因为它可能会通过擦除错误而对我们的程序造成问题。我觉得这是无用的功能,因为discard(x)所做的事情完全相同,而不会对我们的程序造成任何不可预测的行为。

最佳答案

有时错误很有用。您可以使用try: except:捕获这些错误,并根据该段代码是否引起错误来执行不同的操作。例如:

try:
    list.remove(elem)
    print("Item removed!")
except KeyError as e:
    print("Sorry, that item was not in the set. More information: %s".format(str(e)))

关于python - 当python中有.discard(elem)时,为什么要使用.remove(elem)? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50665379/

10-11 06:42