检查列表是否在列表列表中

时间:2015-09-01 14:35:35

标签: python list

我有列表中存储的lat lon点,列表中的点集群以及集群列表,以便:

point1 = [100,50]
point2 = [100,49]
point3 = [120,50]
point4 = [120,49]
cluster1 = [point1,point2]
cluster2 = [point2,point4]
clusterList = [cluster1,cluster2]

我想检查点(作为lat lon列表)是否在群集列表中的任何群集中。如果不是,我想进行操作。

checked = []
for cluster in clusterList:
    if point5 not in cluster:
        checked.append(1)
    else:
        checked.append(0)
if all(checked):
    clusterList.append([point]) 

此解决方案有效,但看起来并不优雅。我想知道是否有办法通过完全避免for循环或不必创建对象“checked”然后检查all()条件来执行此操作。

修改

我想执行一次操作,并且只有当新点不在任何集群中时才会执行。为清楚起见,我正在检查点是否在集群中。如果不是,我为该点创建一个新的集群。

2 个答案:

答案 0 :(得分:3)

你可以这样表达:

sqlite> SELECT * FROM table1 WHERE bar is not 3;
1|2
2|    <---- here it is!!

或者这个:

>>> to_check = [120, 49]
>>> "Not in" if not any(to_check in cluster for cluster in clusterList) else "In"
"In"

注意:我使用>>> to_check = [120, 49] >>> "Not in" if all(to_check not in cluster for cluster in clusterList) else "In" "In" + any()代替not。它比使用all()更快,因为它会快速失败。例如。如果前者发现第一个集群中的点,则不会检查所有其他集群。后者将检查每个簇,即使在第一个簇中找到了点。

UPD 之前的陈述不正确。性能与使用all()相同,因为all()也很懒惰。

答案 1 :(得分:1)

使用sum-flattening hack

>>> [100, 50] in sum(clusterList, [])
True