从自定义索引扩展数组

Extend an array from custom index

我的尝试:

squares = [2**2, 3**2, 4**2, 5**2, 6**2, 7**2, 8**2, 9**2]

print(squares)

squares[:1].extend([1])

print(squares)

输出

[4, 9, 16, 25, 36, 49, 64, 81]

[4, 9, 16, 25, 36, 49, 64, 81]

也可以:

[4, 1, 9, 16, 25, 36, 49, 64, 81]

这是我想要做的事情的一个简化示例(在现实世界中会有更大的数组需要扩展,所以)。

有什么建议请支持

单项:

你可以试试 list.insert:

>>> squares = [2**2, 3**2, 4**2, 5**2, 6**2, 7**2, 8**2, 9**2]
>>> squares.insert(1, 1)
>>> squares
[4, 1, 9, 16, 25, 36, 49, 64, 81]
>>> 

documentation所述:

Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

多项:

试试这个:

squares[1:1] = [1, 2, 3]

要插入数组,可以使用列表切片

squares = [2**2, 3**2, 4**2, 5**2, 6**2, 7**2, 8**2, 9**2]
squares[1:1] = [1]

print(squares) #[4, 1, 9, 16, 25, 36, 49, 64, 81]

为什么没有按预期工作? 看看这个:

squares = [2**2, 3**2, 4**2, 5**2, 6**2, 7**2, 8**2, 9**2]

print(squares)

sub = squares[:1]
sub.extend([1])  # This line does not change `squares`
print(sub)
# [1, 9, 16, 25, 36, 49, 64, 81]

print(squares)
# [4, 9, 16, 25, 36, 49, 64, 81]

如何修复:

squares = [2**2, 3**2, 4**2, 5**2, 6**2, 7**2, 8**2, 9**2]

print(squares)

def insert_elements(origin_list: list, target_list: list, index: int) -> list:
    return origin_list[:index] + target_list + origin_list[index:]

squares = insert_elements(squares, [1], 1)
print(squares)
# [4, 1, 9, 16, 25, 36, 49, 64, 81]