How to remove specific element from sets inside a list using list comprehension

后端 未结 4 1775
天涯浪人
天涯浪人 2021-02-05 03:38

I think this may be related to set being mutable.

Basically, I can remove an element from a set using set.discard(element). However, set.d

4条回答
  •  终归单人心
    2021-02-05 04:06

    Whenever you feel constrained by a method that only works in-place, you can use the behavior of or/and to achieve the semantics that you want.

    [x.discard('') or x for x in test]
    

    This technique is occasionally useful for achieving things in a lambda (or other situations where you are restricted to a single expression) that are otherwise impossible. Whether it's the most "readable" or "pythonic" is debatable :-)

提交回复
热议问题