gpt4 book ai didi

python - 在没有 insert() 或 append() Python 的情况下将项目插入列表

转载 作者:太空宇宙 更新时间:2023-11-03 12:37:23 25 4
gpt4 key购买 nike

我一直在尝试处理一项任务的函数,但我是编码新手。它的一部分是让用户通过输入所需的项目和没有内置功能的索引来将项目插入到列表中。目前,我有代码来替换该索引中的项目,但我无法让它执行预期的操作。

Object是item,list在main函数中。

def add(list, obj, index):
nlist = []
print("Your list ", list)
item = input("Insert item: ")
index = int(input("Index: "))
i = 0
for e in list:
if i < index:
nlist.append(e)
i += 1
elif i == index:
nlist.append(obj)
i += 1
elif i > index:
nlist.append(e)
i += 1
print("Your new list ", nlist)

最佳答案

想象一下,您拥有一套磁性火车。喜欢enter image description here

您想在第二节车厢之后添加一节火车车厢。因此,您需要将索引 12 之间的序列分开,然后将其附加。前面部分是从 0 到 1 的所有内容,第二部分是从 2 到结尾的所有内容。

幸运的是,python 有一个非常好的切片语法:x[i:j] 表示从 i(包括)到 j 的切片(独家的)。 x[:j] 表示从前面到 j 的切片,x[i:] 表示从 i 切片直到最后。

所以我们可以做

def add(lst, obj, index): return lst[:index] + [obj] + lst[index:]

关于python - 在没有 insert() 或 append() Python 的情况下将项目插入列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42936941/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com