13

您好,我已经编写了几个月的代码并且知道基础知识,但是我遇到了一个固定的会员问题,我找不到解决方案。

我有一个整数对列表的列表,我想删除其中包含“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 

我也尝试过使用s.issubset(t)直到我意识到这测试了.st

谢谢!

4

4 回答 4

8

您想测试是否没有交集

if not a & group:

或者

if not a.intersection(group):

或者,相反,这些集合是不相交的:

if a.isdisjoint(group):

方法形式采用任何可迭代的,您甚至不必为此group变成一个集合。以下单线也可以:

groups_no_a = [group for group in groups if a.isdisjoint(group)]

演示:

>>> 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]]

如果您要测试的只是一个元素,那么创建集合的性能可能会比您在成员资格测试中获得的成本更高,并且只需执行以下操作:

3 not in group

group短名单在哪里。

您可以使用该timeit模块来比较 Python 代码片段,以查看最适合您的特定典型列表大小的内容。

于 2013-08-18T15:18:55.113 回答
4

也许你可以使用List Comprehension

a = 3
groups = [[3, 2], [3, 4], [1, 2], [5, 4], [4, 3]]
print [x for x in groups if a not in x]

根据评论编辑:

好吧,对于那些好奇的人,我想做的是;我有一个如下列表: [ [error, [ [group_item_1, group_item_2], [...], [...], [...] ] ], [more like this previous], [... ] ],我想获得错误最少且在 group_item_1 或 group_item_2 中没有“a”的项目。列表已按错误排序。我差不多就可以了:D

这应该可以解决问题:

from itertools import chain, iterfilter

def flatten(listOfLists):
    "Flatten one level of nesting"
    return chain.from_iterable(listOfLists)


errors_list =  [ ['error0', [ [30, 2], [3, 4], [1, 2], [5, 4], [4, 3] ] ], ['error1', [ [31, 2], [3, 4], [1, 2], [5, 4], [4, 3] ] ] ]

a = 30
result = next(ifilter(lambda err: a not in flatten(err[1]), reversed(errors_list)), None)

print result #finds error1 as it has no 30 on its list
于 2013-08-18T15:22:05.223 回答
0

与其创建一个 = set([3]),不如执行以下操作?

a = 3
groups = [[3, 2], [3, 4], [1, 2], [5, 4], [4, 3]]
groups_no_a = [group for group in groups if a not in group]
于 2013-08-18T15:21:24.933 回答
-1

您不需要在这里使用集合,您可以测试列表中元素的成员资格。你似乎也有in,我认为你应该有not in

此代码与您的代码相似,应该可以工作:

## This is the item to test against. 
a = 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:
    if a not in group:
        groups_no_a.append(group)

print groups_no_a

然而,更短、更 Pythonic 的方式使用列表推导:

groups_no_a = [i for i in groups if a not in i]

如果您正在测试一个项目是否在一个更长的列表中,您应该使用集合来代替性能。

于 2013-08-18T15:21:23.073 回答