简体   繁体   中英

how to group by function if any one of the group members has neighbor relationship with another any one of group member in the group?

update1: if same color is neighbor like connected then group them

how to group by function if any one of the group members has neighbor relationship with another any one of group member in the group?

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

Traceback (most recent call last): File "", line 1, in TypeError: isneighborlocation() takes exactly 2 arguments (1 given)

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

The function argument in groupby accepts a single argument, so you have to make use of partial functions to add the 'extra' one.

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

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

but, of course, it means that you have to explicitly test every 'centre'.
Btw, be aware of the sorting requirement on groupby - it seems likely that it may trip you up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM