python里的set的discard和remove的区别
# set 的discard 和 removeset1 = {"apple", "banana", "cherry", "orange", "mango", "grapes"}set1.discard("orange")print('discard1: ', set1) # discard1: {'apple', 'cherry', 'banana', 'mango', 'grapes'}set1.discard("peach")print('discard2: ', set1) # discard2: {'apple', 'cherry', 'banana', 'mango', 'grapes'}set1.remove("cherry")print('remove1: ', set1) # remove1: {'apple', 'banana', 'mango', 'grapes'}set1.remove("peach")print('remove2: ', set1) # Error
使用discard和remove都可以删除set当中的元素,区别就是remove的元素在set当中没有的话会报错,而discard不会。