[英]Python for each element in a list add the value of previous index and next index
[英]How do I replace an element with another new element in the same index and move the previous element to the next index
我有這個問題,我想用一個新元素替換一個元素,而不是刪除我替換的元素,我只是想讓它移動到下一個索引。
import numpy as np
empty_arr = [0] * 5
arr = np.array(empty_arr)
inserted = np.insert(empty_arr, 1, 3)
inserted = np.insert(empty_arr, 1, 4)
#Output:
[0 4 0 0 0 0]
我不知道正確的語法,但我只想用4替換元素3
#Expected Output:
[0 3 4 0 0 0] #move the element 4 to next index
您將第一次插入的結果放在inserted
變量中,但您是從原始數組重新開始進行第二次插入並覆蓋先前的結果。
您應該從上一個結果開始第二次插入:
inserted = np.insert(empty_arr, 1, 3)
inserted = np.insert(inserted, 1, 4)
順便說一句,你必須為此使用 numpy 數組嗎? 常規 Python 列表似乎更適合:
empty_arr = [0] * 5
empty_arr.insert(1,3)
empty_arr.insert(1,4)
print(empty_arr)
[0, 4, 3, 0, 0, 0, 0]
請注意,如果您希望結果中的 3 之后出現 4,則必須在索引 1 處以相反的順序插入它們,或者在索引 1 處插入 3 后在索引 2 處插入 4。
import numpy as np
empty_arr = [0] * 5
arr = np.array(empty_arr)
empty_arr = np.insert(empty_arr, 1, 3)
empty_arr = np.insert(empty_arr, 1, 4)
#output
array([0, 4, 3, 0, 0, 0, 0])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.