如何使用列表理解从列表内的集合中删除特定元素 [英] How to remove specific element from sets inside a list using list comprehension

查看:63
本文介绍了如何使用列表理解从列表内的集合中删除特定元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这可能与设置为mutable有关.

I think this may be related to set being mutable.

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

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 an updated copy conveniently using list comprehension operations?

示例代码:

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

会回来

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

推荐答案

您可以使用 设置差异运算符,像这样

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

这篇关于如何使用列表理解从列表内的集合中删除特定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆