从列表中删除索引元素

时间:2019-11-15 23:54:44

标签: python append element

我正在尝试从列表中删除一个元素,但只能使用range函数和append方法(作业问题)。当索引元素位置不等于position参数时,我的“ for循环”工作正常。但是我似乎无法使我的if语句正常工作到所需的输出。任何帮助将不胜感激。

这是我的代码:

def length(my_list):

    result = 0
    for char in my_list:
        result += 1

    return result

def remove(my_list, position):

    new_list2 = [] # Create a new list
    length2 = length(my_list) # Calls upon the length function

    if position < 0:
        new_list2.append(my_list[position])

    for r in range(length2):
        if r != position:
            new_list2.append(my_list[r])

    if position > length2:
        (my_list)

    return new_list2

str_list5 = ['f','i','r','e']
new_list = remove(str_list5, 2)
print(new_list)
new_list = remove(str_list5, -1)
print(new_list)
new_list = remove(str_list5, 10)
print(new_list)

我在-1和10位置的输出应该是:

['i','r','e']
['f','i','r']

2 个答案:

答案 0 :(得分:0)

从讨论中,我认为超出范围的position值应删除较近的结尾字符。如果是这样,那么您需要正确执行“ clip to the rail”逻辑,并且在执行常规的单字符删除之前:

# A negative position means to remove the first char
if position < 0:
    position = 0
# A large position means to remove the last char
elif position >= length2:
    position = length2 - 1

# With that done, your existing "skip one char" logic should finish the job
for r in range(length2):
    if r != position:
        new_list2.append(my_list[r])

答案 1 :(得分:0)

您可以编写类似以下的函数:

def remove(string, i):
    length = len(string)
    if i > len(string):
        i =  i // length
    elif i < 0:
        i = len(string) - 1
    print([x for index, x in enumerate(string) if index != i])

str_list5 = ['f','i','r','e']   
remove(str_list5, 2)
['f', 'i', 'e']

具有阴性索引:

remove(str_list5, -1)
['f', 'i', 'r']

这个怎么样?

myturn = ['this was cool']
remove(*myturn, 6)
['t', 'h', 'i', 's', ' ', 'w', 's', ' ', 'c', 'o', 'o', 'l']