How to remove an element from a set?

本小妞迷上赌 提交于 2019-12-20 18:01:35

问题


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.discard(element) itself returns None. But I'd like to get a copy of the updated set. For example, if I have a list of sets, how can I get the an updated copy conveniently using list comprehension operations?

Sample code:

test = [{'', 'a'}, {'b', ''}]
print [x.discard('') for x in test]
print test

will return

[None, None]
[set(['a']), set(['b'])]

回答1:


You can use set difference operator, like this

test, empty = [{'', 'a'}, {'b', ''}], {''}
print [x - empty for x in test]
# [set(['a']), set(['b'])]



回答2:


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 :-)




回答3:


>>> s = set( ['a' , 'b', 'c' , 'd' ] )
>>> print(s)
set(['a', 'c', 'b', 'd'])
>>>
>>> s -= {'c'}
>>> print(s)
set(['a', 'b', 'd'])
>>>
>>> s -= {'a'}
>>> print(s)
set(['b', 'd'])



回答4:


This?(duplicate of @thefourtheye answer)

set subtraction operation returns set data.

test = [{'', 'a'}, {'b', ''}]
print [x - {''} for x in test]
print test

Output:

[set(['a']), set(['b'])]
[set(['a', '']), set(['', 'b'])]


来源:https://stackoverflow.com/questions/22877032/how-to-remove-an-element-from-a-set

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!