简体   繁体   中英

numpy array filtering and clubbing elements

I've a numpy array like: [[ 0, 1] [ 1 ,0] [ 2, 30] [ 3, 2] [ 4, 6] [ 5, 31] [ 6, 5] [ 7, 8] [ 8, 7] [ 9, 10] [10, 9] [11, 10] [12 , 1] ]

I want to club common element values found anywhere and make a list like:

[0, 1, 12][2, 30, 3][4, 6, 5, 31][7, 8][9, 10, 11]

Is there any simple way I can achieve this?

You can do something like as follows:

input_list = [[0, 1], [1, 0], [2, 30], [3, 2], [4, 6], [5, 31], [6, 5], 
                [7, 8], [8, 7], [9, 10], [10, 9], [11, 10], [12 , 1]]
result = []
for i in range(len(input_list)):
    if not result:
        result.append(set(input_list[i]))
    else:
        flag = False
        last_merged_index = -1
        j = 0
        while j < len(result):
            if not set(input_list[i]).isdisjoint(result[j]):
                result[j] |= set(input_list[i])
                flag = True
                if last_merged_index != -1:
                    result[j] |= result[last_merged_index]
                    result.pop(last_merged_index)
                    last_merged_index = j-1
                else:
                    last_merged_index = j
                    j += 1
            else:
                j += 1
        if not flag:
            result.append(set(input_list[i]))

print(result)

Output:

[{0, 1, 12}, {2, 3, 30}, {4, 5, 6, 31}, {8, 7}, {9, 10, 11}]

For your second input:

input_list = [[0, 1], [1, 0], [2, 30], [3, 2], [4, 6], [5, 31], [6, 5], [7, 8], [8, 7], [9, 10], [10, 9], [11, 10], [12 , 1], 
[13, 14], [14, 16], [15, 16], [16, 14], [17, 18], [18, 17], [19, 20], [20, 21], [21, 23], [22, 26], [23, 21], [24, 23], [25, 24], 
[26, 27], [27, 26], [28, 29], [29, 28], [30, 2], [31, 2]]

You should get the following:

[{0, 1, 12}, {2, 3, 4, 5, 6, 30, 31}, {8, 7}, {9, 10, 11}, {16, 13, 14, 15}, {17, 18}, {19, 20, 21, 23, 24, 25}, {26, 27, 22}, {28, 29}]

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