您好我已经编写了几个月了,并且知道了基础知识,但是我遇到了一个集合成员问题,我无法找到解决方案.
我有一个整数对列表的列表,我想删除其中包含"a"整数的列表.我认为使用套装是最简单的方法.贝娄是代码:
## This is the item to test against.
a = set([3])
## This is the list to test.
groups = [[3, 2], [3, 4], [1, 2], [5, 4], [4, 3]]
## This is a list that will contain the lists present
## in groups which do not contain "a"
groups_no_a = []
for group in groups:
group = set(group)
if a in group:
groups_no_a.append(group)
## I thought the problem had something to do with
## clearing the variable so I put this in,
## but to no remedy.
group.clear()
print groups_no_a
Run Code Online (Sandbox Code Playgroud)
我一直在使用也尝试s.issubset(t)直到我意识到这一点,如果测试的每一个在元素s中t.
谢谢!
你想测试是否没有交叉点:
if not a & group:
Run Code Online (Sandbox Code Playgroud)
要么
if not a.intersection(group):
Run Code Online (Sandbox Code Playgroud)
或者,相反,这些集合是不相交的:
if a.isdisjoint(group):
Run Code Online (Sandbox Code Playgroud)
方法形式采用任何迭代,你甚至不必group变成一个集合.以下单行也可以使用:
groups_no_a = [group for group in groups if a.isdisjoint(group)]
Run Code Online (Sandbox Code Playgroud)
演示:
>>> a = set([3])
>>> groups = [[3, 2], [3, 4], [1, 2], [5, 4], [4, 3]]
>>> [group for group in groups if a.isdisjoint(group)]
[[1, 2], [5, 4]]
Run Code Online (Sandbox Code Playgroud)
如果您要测试的只是一个元素,那么创建集合的性能可能会比您在成员资格测试中获得的成本更高,而且只是:
3 not in group
Run Code Online (Sandbox Code Playgroud)
哪里group是一个简短的清单.
您可以使用该timeit模块比较Python代码片段,以查看哪种方法最适合您的特定典型列表大小.
| 归档时间: |
|
| 查看次数: |
24696 次 |
| 最近记录: |