Python 如何从集合中删除元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22877032/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove an element from a set?
提问by Zhen Sun
I think this may be related to set being mutable.
我认为这可能与设置为有关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?
基本上,我可以使用set.discard(element). 但是,set.discard(element)本身返回None。但我想获得更新集的副本。例如,如果我有一个集合列表,如何使用列表理解操作方便地获取更新的副本?
Sample code:
示例代码:
test = [{'', 'a'}, {'b', ''}]
print [x.discard('') for x in test]
print test
will return
将返回
[None, None]
[set(['a']), set(['b'])]
采纳答案by thefourtheye
You can use set difference operator, like this
您可以使用设置差异运算符,像这样
test, empty = [{'', 'a'}, {'b', ''}], {''}
print [x - empty for x in test]
# [set(['a']), set(['b'])]
回答by roippi
Whenever you feel constrained by a method that only works in-place, you can use the behavior of or/andto achieve the semantics that you want.
每当您感到受限于只能就地工作的方法时,您可以使用or/的行为and来实现您想要的语义。
[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 :-)
这种技术有时可用于实现在lambda其他情况下不可能实现的事情(或其他限制为单个表达式的情况)。无论是最“可读”还是“pythonic”都是有争议的:-)
回答by Kei Minagawa
This?(duplicate of @thefourtheye answer)
这个?(@thefourtheye 答案的重复)
setsubtraction operation returns setdata.
set减法运算返回set数据。
test = [{'', 'a'}, {'b', ''}]
print [x - {''} for x in test]
print test
Output:
输出:
[set(['a']), set(['b'])]
[set(['a', '']), set(['', 'b'])]
回答by jxramos
>>> 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'])

