在数组中的特定位置插入

2024-10-05 14:27:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数组[ 0 10 15 20 10 0 35 25 15 35 0 30 20 25 30 0],我需要在增量为5的位置插入另一个数组“[5,7,8,15]”的每个元素,以便最终数组看起来[ 0 10 15 20 5 10 0 35 25 7 15 35 0 30 8 20 25 30 0 15] length is 20

我正在尝试使用此代码

arr_fla = [ 0 10 15 20 10  0 35 25 15 35  0 30 20 25 30  0]
arr_split = [5,7,8,15]
node = 5   
    node_len = node * (node-1)
    
    for w in range(node, node_len, 5):
        for v in arr_split:
            arr_fla = np.insert(arr_fla,w,v)
    print(arr_fla)

我得到的结果是

'[ 0 10 15 20 10 15  8  7  5  0 15  8  7  5 35 15  8  7  5 25 15 35  0 30
 20 25 30  0]' length 28

谁能告诉我哪里出了问题


Tags: 代码innode元素forlenisnp
3条回答

如果大小像示例中一样整齐排列,则可以使用reshape

np.reshape(arr_fla,(len(arr_split),-1))
# array([[ 0, 10, 15, 20],
#        [10,  0, 35, 25],
#        [15, 35,  0, 30],
#        [20, 25, 30,  0]])

。。。将arr_split追加为新列

np.c_[np.reshape(arr_fla,(len(arr_split),-1)),arr_split]
# array([[ 0, 10, 15, 20,  5],
#        [10,  0, 35, 25,  7],
#        [15, 35,  0, 30,  8],
#        [20, 25, 30,  0, 15]])

。。。然后再变平

np.c_[np.reshape(arr_fla,(len(arr_split),-1)),arr_split].ravel()
# array([ 0, 10, 15, 20,  5, 10,  0, 35, 25,  7, 15, 35,  0, 30,  8, 20, 25,
#        30,  0, 15]) 

我已经纠正了它:

arr_fla = [0,10,15,20,10,0,35,25,15,35,0,30,20,25,30,0]
arr_split = [5,7,8,15]
node = 5
    
for w in range(len(arr_split)):
    arr_fla = np.insert(arr_fla, (w+1)*node-1, arr_split[w])
print(arr_fla)

'''
Output:
[ 0 10 15 20  5 10  0 35 25  7 15 35  0 30  8 20 25 30  0 15]
'''

在代码中:

for v in arr_split:

这将一次获取所有元素(总共w次),但一次只需要一个元素。因此,您不需要额外的for循环

您希望在每次从第二个数组arr_split插入项时,计数器都会不断上升

试试这个代码。我的假设是,可以直接插入最后一个元素,因为原始数组只有16个元素

arr_fla = [0,10,15,20,10,0,35,25,15,35,0,30,20,25,30,0]
arr_split = [5,7,8,15]

j = 0 #use this as a counter to insert from arr_split

#start iterating from 4th position as you want to insert in the 5th position

for i in range(4,len(arr_fla),5): 

    arr_fla.insert(i,arr_split[j]) #insert at the 5th position every time
    #every time you insert an element, the array size increase

    j +=1 #increase the counter by 1 so you can insert the next element

arr_fla.append(arr_split[j]) #add the final element to the original array 
print(arr_fla)

输出:

[0, 10, 15, 20, 5, 10, 0, 35, 25, 7, 15, 35, 0, 30, 8, 20, 25, 30, 0, 15]

相关问题 更多 >