首页 > 解决方案 > 将多次整数添加到列表的中间

问题描述

我想将c时间b整数添加到列表的中间。这是我的代码:

listA.insert(int(len(listA)/2),b*c)
print("Your New List: ", listA)

当我更改它时(b*c)([b]*c)它可以工作,但我稍后会将它转换为整数。因此,它必须是像[1,2,3,4,5]not这样的正式形式[1,2,[3],4,5]。如果我们说listA = [1,2,3,4,5],让我们假设b = 2c = 3我需要有[1,2,2,2,2,3,4,5]。另外,我无权使用循环。

标签: pythonpython-3.x

解决方案


使用列表切片:

lst = [1,2,3]
middle = len(lst) // 2
lst[middle:middle] = [2] * 10

输出:

[1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3]

推荐阅读