在列表中的另一个值之后插入一个值

时间:2018-03-24 12:31:56

标签: python list

我想要一个名为insert_after的函数,它会获取一个列表和两个值(search_valuevalue)。

然后,功能应该是在第一次出现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)

5 个答案:

答案 0 :(得分:5)

您需要先在列表中找到search_value的索引,这可以使用.index方法完成。然后,您可以使用.insert方法将value插入其后的位置(索引+1)。

但是,我们需要考虑search_valuelst 的情况。为此,我们只需使用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方法是正确的方法,因为它为我们提供了该值的索引 - 允许我们使用{{ 1}}正确。

如果您不想使用.insert

,该怎么办?

所以,是的,你可以使用.index,但不是像你一样迭代这些术语,你真的想要迭代值和索引。这可以使用for-loop来实现。

所以,我会让你自己把它放在一个函数中,因为你可能最终会使用enumerate()方法,但基本的想法是:

.index

答案 1 :(得分:1)

insert =>的语法list1.insert(指数,元素);

但是你在这里指定search_value。你也可以使用index函数来获取列表中值的索引。

函数看起来像这样。

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。

答案 2 :(得分:0)

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)

答案 3 :(得分:0)

要实现这一点,您需要获取要插入值的点的索引值。

def insert_after(myList, i, j):
    try:
        myList.insert(myList.index(i)+1, j)
    except ValueError:
        myList.append(j)

你可以在这里阅读更多关于列表的内容; https://docs.python.org/2/tutorial/datastructures.html

答案 4 :(得分:0)

另一种方法是使用生成器查找插入索引。这允许提供默认值来隐藏list.index的异常处理。

以下是创建新列表的解决方案。

def insert_after(list1, search_value, value):
    i = next((i + 1 for i in range(len(list1)) if list1[i] == search_value), len(list1))
    return [*list1[:i], value, *list1[i:]]

insert_after([1, 2, 3], 2, 'foo') # [1, 2, 'foo', 3]
insert_after([1, 2, 3], 10, 'bar') # [1, 2, 3, 'bar']

这是改变现有列表的解决方案。

def insert_after(list1, search_value, value):
    i = next((i + 1 for i in range(len(list1)) if list1[i] == search_value), len(list1))
    list1.insert(i, value)

list1 = [1, 2, 3]
insert_after(list1, 2, 'foo')

list1 # [1, 2, 'foo', 3]