当前位置:   article > 正文

python里的set的discard和remove的区别_python中remove和discard的区别

python中remove和discard的区别

python里的set的discard和remove的区别

  1. # set 的discard 和 remove
  2. set1 = {"apple", "banana", "cherry", "orange", "mango", "grapes"}
  3. set1.discard("orange")
  4. print('discard1: ', set1) # discard1: {'apple', 'cherry', 'banana', 'mango', 'grapes'}
  5. set1.discard("peach")
  6. print('discard2: ', set1) # discard2: {'apple', 'cherry', 'banana', 'mango', 'grapes'}
  7. set1.remove("cherry")
  8. print('remove1: ', set1) # remove1: {'apple', 'banana', 'mango', 'grapes'}
  9. set1.remove("peach")
  10. print('remove2: ', set1) # Error

使用discard和remove都可以删除set当中的元素,区别就是remove的元素在set当中没有的话会报错,而discard不会。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/344202
推荐阅读
相关标签
  

闽ICP备14008679号