numpy阵列过滤和夜总会元素

时间:2017-11-09 09:37:20

标签: python numpy

我有一个像numpy数组: [[ 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] ]

我想在任何地方找到共同的元素值,并列出如下列表:

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

有什么简单的方法可以达到这个目的吗?

1 个答案:

答案 0 :(得分:2)

您可以执行以下操作:

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)

输出:

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

第二次输入:

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

你应该得到以下信息:

[{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}]