如果任何一个组成员与组中任何一个组成员有邻居关系,如何按功能分组?



update1: 如果相同的颜色是邻居,就像连接一样,然后将它们分组

如果任何一个组成员与组中任何一个组成员有邻居关系,如何按功能分组?

if x coordinate same and y coordinate difference is 1 then return 1 #same memeber
if y coordinate same and x coordinate difference is 1 then return 1 #same memeber
else return 0 #not group memeber

回溯(最近一次调用(: 文件 ",第 1 行,在 类型错误: isneighborlocation(( 正好需要 2 个参数(给定 1 个(

from itertools import groupby 
testing1 = [(1,1),(2,3),(2,4),(3,5),(3,6),(4,6)] 
def isneighborlocation(lo1, lo2): 
if abs(lo1[0] - lo2[0]) == 1  or lo1[1] == lo2[1]: 
return 1 
elif abs(lo1[1] - lo2[1]) == 1  or lo1[0] == lo2[0]: 
return 1 
else: 
return 0 
groupda = groupby(testing1, isneighborlocation) 
for key, group1 in groupda: 
print key 
for thing in group1: 
print thing 

expect output 3 group 
group1 [(1,1)] 
group2 [(2,3),(2,4)] 
group3 [(3,5),(3,6),(4,6)] 

groupby中的函数参数接受单个参数,因此您必须使用部分函数来添加"额外"参数。

https://docs.python.org/3/library/functools.html#functools.partial

from functools import partial 
...
groupda = groupby(testing1, partial(isneighborlocation, centre))

但是,当然,这意味着你必须明确测试每个"中心"。
顺便说一句,请注意分组的排序要求 - 它似乎可能会绊倒您。

相关内容

最新更新