简体   繁体   中英

how to find connected values in an array?

I have an array like this:

array([[0, 1],
       [0, 2],
       [0, 4],
       [2, 4],
       [3, 4],
       [5, 6]])

The connected values are defined as those who pair with each other, or with a shared value, for example, 1 and 2 are connected because they pair with the same value 0 .

So the output I wanna get is like this (any data type will do):

{0,1,2,3,4}, {5,6} .

TIA.

One way to do this would be to create a list of sets, and add values from the list into the sets based on overlap with existing values in the set; if there is no overlap, pushing a new set into the list:

def group_values(vals):
    
    def group_val(vals):
        sets = []
        for val in vals:
            for s in sets:
                if any(v in s for v in val):
                    s.update(val)
                    break
            else:
                sets.append(set(val))
        return sets

    sets = group_val(vals)
    # check if any more merging is required
    newsets = group_val(sets)
    while len(newsets) != len(sets):
        sets = newsets
        newsets = group_val(sets)
    return sets
   
vals = [[0, 1], [0, 2], [0, 4], [2, 4], [3, 4], [5, 6]]
print([s for s in group_values(vals)])
vals = [[0, 1], [0, 2], [0, 4], [2, 4], [3, 4], [5, 6], [8, 6], [7, 4], [7, 6], [7, 8]]
print([s for s in group_values(vals)])

Output:

[{0, 1, 2, 3, 4}, {5, 6}]
[{0, 1, 2, 3, 4, 5, 6, 7, 8}]

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