python - 有没有办法在 def 函数中使列表插入和列表弹出?
问题描述
我想制作一个与列表插入和列表弹出具有相同效果的 def 函数。
首先,列表插入没有返回值。我做了一个 def list_insert。
def list_insert(lst, index, obj, /):
lst = [1, 2, 3]
lst_insert(lst, 1, 6)
其次,List pop 有返回值。我制作了一个 def list_pop。
def list_pop(lst, index=-1, /):
lst = [1, 2, 3]
list_pop(lst, 1)
但我不知道如何在 def 函数中解开这些方法。
解决方案
您可以使用切片分配:
def list_insert(lst, index, obj, /):
lst[index:index] = [obj]
lst = [1, 2, 3]
list_insert(lst, 1, 6)
lst
# [1, 6, 2, 3]
def list_pop(lst, index=-1, /):
if 0 <= index < len(lst):
lst[:] = lst[:index] + lst[index+1:]
else:
raise IndexError
lst = [1, 2, 3]
list_pop(lst, 1)
lst
# [1, 3]
推荐阅读
- c++ - 如何在遍历时添加要设置的元素?
- json - JSON.parse 从 Web api 返回 undefined
- xamarin - Xamarin 使用 Skia Sharp 形成 Dotted Circle
- javascript - 谷歌分析没有收集任何网站速度数据
- cplex - 使用 cplex OPL 对时空网络进行建模
- git - 除了最后一次提交删除之前的所有提交
- c# - 使用 Excel 互操作时忽略 Excel 中设置的日期格式
- batch-file - 我们可以在不使用 for 循环的情况下仅提取字符串“04.07.2019 16:56:21”中的年份吗?
- javascript - 如何获取函数的返回错误值?(反应原生)
- java - giving child of firebase database name equal to USER ID key