python - 列表插入和变异
问题描述
def new_insert(lst, i, e):
lst = lst[:i] + [e] + lst[i:]
a = [0, 1, 2, 3, 4, 6, 7]
new_insert(a, 5, 5)
#Expected output: a = [0, 1, 2, 3, 4, 5, 6, 7]
b = ['0', '1', '0']
new_insert(b, 0, '1')
#Expected output: b = ['1', '0', '1', '0']
new_insert([1,2,3], 1, 0)
#Expected output = None
对于上面的代码,将e添加到列表中时,我无法得到新修改列表的答案。当 e = 0 时,输出应返回 None。如何更改代码,以便获得预期的输出?
解决方案
选项 1:
您需要从以下位置返回修改后的列表new_insert
:
def new_insert(lst, i, e):
return lst[:i] + [e] + lst[i:]
然后做:
a = [0, 1, 2, 3, 4, 6, 7]
a = new_insert(a, 5, 5)
选项 2:
或者只是这样做:
def new_insert(lst, i, e):
lst[:] = list[:i] + [e] + lst[i:]
如果您不想从函数中返回它。
推荐阅读
- r - eval 中的错误(predvars、data、env):找不到对象“gdp”
- scala - 将过滤器作为参数传递给 Dataframe.filter 函数
- python - 没有 OOP 的 GUI 编程
- redis - 在 ioredis 上使用“zrevrange”和“scale reads: slaves”的问题
- mysql - 如何在 laravel 中编写此查询
- c# - 调用 aspx 页面的 EXE 程序获取:401 - 未经授权:由于凭据无效,访问被拒绝
- c# - 托管 C# 代码未发生非托管调用
- xamarin - NavigationPage BarBackgroundColor 在 Xamarin.Android 上不起作用
- php - 如何根据整数值将数组拆分为两个数组
- javascript - 1秒内多次调用Google App Script onEdit函数失败