如何从集合中移除元素?

2024-06-08 04:41:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我认为这可能与set是mutable有关。

基本上,我可以使用set.discard(element)从集合中移除元素。但是,set.discard(element)本身返回None。但我想得到一份最新版本的拷贝。例如,如果我有一个集合列表,如何使用列表理解操作方便地获取更新的副本?

示例代码:

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

会回来的

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

Tags: 代码test版本none元素示例列表for
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'])

每当您感到被一个只起作用的方法所约束时,您可以使用or/and的行为来实现您想要的语义。

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

这种技术有时对于在lambda(或其他限制为单个表达式的情况)中实现本来不可能实现的事情非常有用。它是最“可读”还是“Python”是有争议的:-)

您可以使用set difference operator,如下所示

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

相关问题 更多 >

    热门问题