根据python中的列表重新排列数组元素

xiaoxingxing pytorch 453

原文标题rearrange an array element based on list in python

我有一个二维数组a,大小2, 1403和一个列表b,它有 2 个列表。

a.shape = (2, 1403) # a is 2D array, each row has got unique elements.

len(b) = 2 # b is list

len(b[0]), len(b[1]) = 415, 452 # here also both the list inside b has got unique elements

b[0] and b[1]中存在的所有元素分别存在于a[0] and a[1]

现在我想根据b的元素重新排列a的元素。我想重新排列,使得b[0]中的所有元素也出现在a[0]中,都应该出现在a[0]的结尾,意思是新的a应该是这样的a[0][:-len(b[0])] = b[0],同样地a[1][:-len(b[1])] = b[1]

玩具示例

a有像[[1,2,3,4,5,6,7,8,9,10,11,12],[1,2,3,4,5,6,7,8,9,10,11,12]这样的元素

b有像[[5, 9, 10], [2, 6, 8, 9, 11]]这样的元素

new_a变成[[1,2,3,4,6,7,8,11,12,5,9,10], [1,3,4,5,7,10,12,2,6,8,9,11]]

我编写了一个代码,它遍历所有变得非常慢的元素,如下所示

a_temp = []
remove_temp = []
for i, array in enumerate(a):
    a_temp_inner = []
    remove_temp_inner = []
    for element in array:
        if element not in b[i]:
            a_temp_inner.append(element) # get all elements first which are not present in b
        else:
            remove_temp_inner.append(element) #if any element present in b, remove it from main array

    a_temp.append(a_temp_inner)
    remove_temp.append(b_temp_inner)

a_temp = torch.tensor(a_temp)
remove_temp = torch.tensor(remove_temp)
a = torch.cat((a_temp, remove_temp), dim = 1) 

谁能帮我做一些比这更好的更快的实现

原文链接:https://stackoverflow.com//questions/71542505/rearrange-an-array-element-based-on-list-in-python

回复

我来回复
  • paul-shuvo的头像
    paul-shuvo 评论

    这是我的方法:

    index_ = np.array([[False if i in d else True for i in c] for c, d in zip(a,b)])
    arr_filtered =[[np.extract(ind, c) for c, d, ind in zip(a,b,index_)], [np.extract(np.logical_not(ind), c) for c, d, ind in zip(a,b, index_)]]
    arr_final = ar = np.array([np.concatenate((i, j)) for i, j in zip(*arr_filtered)])
    
    2年前 0条评论
  • 假设gais anp.array,bis alist你可以使用

    np.array([np.concatenate((i[~np.in1d(i, j)], j)) for i, j in zip(a,b)])
    

    输出

    array([[ 1,  2,  3,  4,  6,  7,  8, 11, 12,  5,  9, 10],
           [ 1,  3,  4,  5,  7, 10, 12,  2,  6,  8,  9, 11]])
    

    如果bcontains empty,可以进行微优化lists

    np.array([np.concatenate((i[~np.in1d(i, j)], j)) if j else i for i, j in zip(a,b)])
    

    在我的基准测试中,对于np.arrays少于 ~100 个元素的转换.tolist()np.concatenate

    np.array([i[~np.in1d(i, j)].tolist() + j for i, j in zip(a,b)])
    

    此解决方案的数据示例和导入

    import numpy as np
    
    a = np.array([
            [1,2,3,4,5,6,7,8,9,10,11,12],
            [1,2,3,4,5,6,7,8,9,10,11,12]
        ])
    b = [[5, 9, 10],
         [2, 6, 8, 9, 11]]
    
    2年前 0条评论