python - 将多次整数添加到列表的中间
问题描述
我想将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 = 2
,c = 3
我需要有[1,2,2,2,2,3,4,5]
。另外,我无权使用循环。
解决方案
使用列表切片:
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]
推荐阅读
- python - 如何在函数内部使用我们在函数外部定义的变量
- reactjs - Material UI 的 React 评分组件是如何在表单中使用的?
- flutter - 使用 TextField 时不正确使用 ParentDataWidget
- c++ - 为什么内部类和外部类不能同名?
- python - 如何将 urllib.request.urlopen() 与 add_hotkey() 一起使用?
- css - 适用于没有媒体查询的移动设备的 CSS Grid 单列布局
- django - 当前路径,与其中任何一个都不匹配
- mysql - “SELECT id, title, @natusort:=@natusort + 1 AS ordercount”没有按预期增加
- amazon-web-services - Terraform AWS:无法将先前创建的 root_block_device 与使用 aws_launch_configuration 启动的 AWS EC2 实例重用
- python - 熊猫数据框