我正在编写一个程序,将元素插入到特定索引之前的位置的列表中。例如,
mylist = [1,2,3,4,5]
enter the index = 3
enter the item = 7
输出:
[1,2,3,7,4,5]
由于输入索引是3,python会在位置index-1处附加新项目,即2。
我尝试了类似的东西,但输出似乎有些偏差:
mylist = [1,2,3,4,5]
indexInput = int(input("Enter the index: "))
itemInput = int(input("Enter the item: "))
for i in mylist:
new_slot = indexInput -1
new_length = len(mylist) + 1
if i == new_slot:
mylist[i] = item
mylist.append(mylist[i])
print(mylist)
我知道python中的insert()函数,但我不允许使用它,所以我必须编写很长的代码。非常感谢任何帮助。
答案 0 :(得分:2)
你可以使用列表切片:
mylist = [1,2,3,4,5]
indexInput = int(input("Enter the index: "))
itemInput = int(input("Enter the item: "))
if indexInput<0:
indexInput = len(mylist)+indexInput+1
mylist = mylist[:indexInput] + [itemInput] + mylist[indexInput:]
print(mylist)
# for index 3 and item 7 => [1, 2, 3, 7, 4, 5]
# for index -2 and item 6 => [1, 2, 3, 4, 6, 5]
说明:
list[start:end:step] => list items from index [start] to index [end-1] with a step of 1
if start is not given, 0 is assumed, if end is not given, it goes all the way to the end of the list, if step is not given, it assumes a step of 1
In my code I wrote:
mylist = mylist[:indexInput] + [itemInput] + mylist[indexInput:]
for indexInput=3 and itemInput=7
mylist = mylist[:3] + [7] + mylist[3:]
mylist[:3] => mylist from 0 (start not given), to 3-1, step of 1 (step not given)
list1 + list2 => a list that contains elements from list1 and list2
mylist[:3] + [7] => [...elements of mylist[:3]..., 7]
mylist[3:] => mylist from 3, to len(mylist)-1 (end not given), step of 1 (step not given)
如果你想做很长的路,这是一个解决方案:
mylist = [1,2,3,4,5]
indexInput = int(input("Enter the index: "))
itemInput = int(input("Enter the item: "))
if indexInput<0:
indexInput = len(mylist)+indexInput+1
leftSide = []
rightSide = []
for i in range(len(mylist)):
if i<indexInput:
leftSide.append(mylist[i])
elif i>indexInput:
rightSide.append(mylist[i])
else:
leftSide.append(itemInput)
leftSide.append(mylist[i])
mylist = leftSide + rightSide
print(mylist)
# for index 3 and item 7 => [1, 2, 3, 7, 4, 5]
# for index -2 and item 6 => [1, 2, 3, 4, 6, 5]
答案 1 :(得分:0)
这是我的代码
mylist = [1, 2, 3, 4, 5]
indexInput = int(input("Enter the index: "))
itemInput = int(input("Enter the item: "))
for idx, val in enumerate(mylist):
if idx == indexInput:
mylist = mylist[:idx] + [itemInput] + mylist[idx:]
print(mylist)
希望它可以帮助您,只需使用enumerate
函数来获取mylist
索引
答案 2 :(得分:0)
list = [1,2,3,4,5]
inputIndex = 3
inputItem = 7
temp = 0
for i in range(len(list)):#continuously swap your elements until you reach the end
if(i == len(list) - 1): # if you're at the end, swap and add the temp to the end
temp = list[i]
list[i] = inputItem
list.append(temp)
elif(i >= inputIndex):
temp = list[i]
list[i] = inputItem
inputItem = temp
print(list)
这可能是你正在寻找的,如果这是一个你不允许使用insert
的作业,那么我假设你可能不允许使用切片