如何在不使用内置函数的情况下通过Python中的索引从列表中删除元素

时间:2017-09-24 05:19:51

标签: python list

我的家庭作业是:

  • 编写一个名为remove(my list, position)的函数,该函数将列表和位置作为参数。
  • 该函数返回列表的副本,其中的项目位于指定的索引处,从列表中删除。
  • 检查超出列表(my list)边界的位置值。
    • 如果位置大于列表的长度,请删除列表末尾的项目。
    • 如果位置小于或等于零,则删除存储在列表开头的项目。
  • 您必须在解决方案中使用循环。
  • 您必须使用:
    • 内置函数(range()函数除外),
    • 切片表达式,
    • 列出方法,或
    • 字符串方法
    • 在您的解决方案中。

我只能使用len()功能和range()

我不明白如何完成这项任务。

4 个答案:

答案 0 :(得分:1)

通过使用范围遍历枚举列表,您可以在一个位置创建一个没有元素的新列表。

def remove(my_list, position):
    l = len(my_list)

    if position >= l:
       position = l - 1
    elif position <= 0:
       position = 0

    return [my_list[i] for i in range(l) if i != position]

>>>remove([1,2,3,4], 5)
[1, 2, 3]
>>>remove([1,2,3,4], -1)
[2, 3, 4]
>>>remove([1,2,3,4], 1)
[1, 3, 4]

答案 1 :(得分:1)

我们可以将range()抛弃为另一个邪恶的内置函数,并通过使用隐式循环而不是显式循环来避免复杂的理解:

def remove(my_list, position):
    length = len(my_list)

    if position < 0:
        position = 0
    elif position >= length:
        position = length - 1

    def remove_recursive(my_list, position):
        if my_list:
            head, *tail = my_list
            if position == 0:
                return tail
            return [head] + remove_recursive(tail, position - 1)

        return my_list

    return remove_recursive(my_list, position)

答案 2 :(得分:0)

注意:此处的位置从索引1开始,所以基于此做。

www.fredosaurus.com

注2:此处仅使用def remove(l,pos): pos-=1 #convert pos to starting index 0 size=len(l) if pos <= 0: return [l[i] for i in range(1,size)] if pos >= size: return [l[i] for i in range(size-1)] return [l[i] for i in range(size) if i!=pos] #driver function l=[1,2,3,4] print(remove(l,0)) #If the position is less than or equal to zero, remove the item stored at the start of the list #[2, 3, 4] print(remove(l,1)) #[2, 3, 4] print(remove(l,2)) #[1, 3, 4] print(remove(l,5)) #If the position is greater than the length of the list, remove the item at the end of the list #[1, 2, 3] len()个功能。

答案 3 :(得分:0)

这提供了所需的解决方案。您可以使用内置的len而不是``my_len'。我在编辑之前就这样做了。

def my_len(sequence):
    """(sequence)->int
    Return the length of a sequence e.g. lists, strings, e.t.c
    """
    seq_length = 0
    for i in sequence:
        seq_length += 1
    return seq_length

def remove(my_list, position):
    """(sequence)->sequence
    Return a sequence with the item at position ``position' removed.
    If the sequence length is larger (or smaller) than position,
    remove the last element.

    Dependencies: my_len

    >>> xs = list(range(10))
    >>> remove(xs, 5)
    [0, 1, 2, 3, 5, 6, 7, 8, 9]
    >>> remove(xs, 11)
    [0, 1, 2, 3, 4, 5, 6, 7, 8]
    >>> remove(xs, -5)
    [1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>> remove(xs, 0)
    [1, 2, 3, 4, 5, 6, 7, 8, 9]
    """
    lst = []
    list_len = my_len(my_list)
    if position <= 0:
    rm_idx = 0
    elif position >= list_len:
        rm_idx = list_len - 1
    else:
        rm_idx = position - 1
    for i in range(list_len):
        if i != rm_idx:
            lst += [my_list[i]]
    return lst