我想要一个名为insert_after的函数,它将接受一个列表和两个值(search_value和value)。
功能应该是在第一次出现value之后插入search_value。
如果search_value不在列表中,那么将其添加到末尾。我想使用一个try...except语句来完成这个任务。
例如,如果列表是:
myList = [4,2,6,7,8,1], 然后函数调用:
insert_after(myList, 7, 5)应返回:
[4,2,6,7,5,8,1]我已经尝试过了,但是即使我指定了索引,我的值仍然会被插入到列表的末尾。
def insert_after(list1, search_value, value):
try:
for i in list1:
if i == search_value:
list1.insert(search_value+1,value)
else:
list1.insert(len(list1)+1,value)
except:
list1.insert(len(list1)+1,value)发布于 2018-03-24 12:40:10
您需要首先在列表中找到search_value的索引,这可以使用.index方法来完成。然后,可以使用.insert方法在该位置插入value (索引+1)。
但是,我们需要考虑search_value不在lst中的情况。为此,我们只需使用try...except来捕获ValueError,以便在.index失败时使用。而且,在本例中,我们希望将其追加到lst或.insert的末尾,这两种方法都有效。
def insert_after(lst, search_value, value):
try:
lst.insert(lst.index(search_value)+1, value)
except ValueError:
lst.append(search_value)
#or: lst.insert(len(lst)-1, value)还有一项测试:
>>> l = [4, 2, 6, 7, 8, 1]
>>> insert_after(l, 7, 5)
>>> l
[4, 2, 6, 7, 5, 8, 1]为什么你的方法不起作用?
如果我们仔细看一下你的主插入线:
list1.insert(search_value+1,value)我们可以看到你的逻辑有点偏离。.insert方法接受一个索引和一个值。在这里,您将search_value+1作为索引传递,尽管这实际上只是值。
因此,希望您可以从我的代码中看到,使用.index方法是正确的方法,因为它给出了该值的索引--允许我们正确地使用.insert。
如果您不想使用.index__怎么办?
所以,是的,您可以使用一个for-loop,但是您不需要像现在这样迭代这些术语,而是真正地希望对值和索引进行迭代。这可以使用enumerate()来实现。
因此,我将让您自己将其放入一个函数中,因为您很可能最终将使用.index方法,但是基本思想应该是这样的:
for i, e in enumerate(lst):
if e == search_value:
lst.insert(i+1, value)发布于 2018-03-24 12:41:32
插入=>列表的语法。插入(索引,元素);
但是在这里您可以指定search_value.and,也可以使用索引函数来获取列表中值的索引。
函数看起来是这样的。
def insert_after(list1, search_value, value):
try:
index = list1.index(search_value);
list1.insert(index+1,value);
except:
list1.insert(len(list1)+1,value)当列表中不存在值时,它将引发ValueError。
发布于 2018-03-24 12:40:42
def get_index(mylist, search_value):
"""return index number; returns -1 if item not found"""
try:
return mylist.index(search_value)
except ValueError as ve:
# ValueError would be thrown if item not in list
return -1 # returns -1 if item not in list
def insert_after(list1, search_value, value):
index = get_index(list1, search_value)
if index != -1:
"""inserts after index"""
list1.insert(index + 1, value)
else:
"""appends to the end of list"""
list1.append(value)https://stackoverflow.com/questions/49464719
复制相似问题