在列表中找到 int 后删除索引 - Python

Remove indice after finding int in list - Python

我有一个脚本可以在给定列表中搜索数字 13。如果找到 13,则需要将其删除,但我还需要删除它后面的索引。我找到了所有 13 并删除了它们,但我不确定在它之后删除索引的最佳方法。我知道我需要先删除 13 之后的索引,因为删除后会发生移位。最后我需要 return 所有指数的总和,我已经完成了。

这是我在 Codebat.com 中进行的一项挑战,它不允许导入。

这是我的资料:

def sum13(nums):
    #Return 0 for empty lists
    if nums == '':
        return 0

    #Find 13s, remove next index and then index of 13
    while(True):
        if 13 in nums:
            #remove the index after 13 here
            nums.remove(13)         
        else:
            break

    #Return the sum of all indices.  
    else:
        return sum(nums)

输入是随机的整数列表,例如:

sum13([13, 1, 2, 13, 2, 1, 13]) # Expected Outcome: 3
sum13([1, 2, 13, 2, 1, 13])     # Expected Outcome: 4

为了获得下一个索引,我在 for 循环中尝试了 nums.index(i+1) 的变体,这只会产生错误,并且一直在尝试列表理解和枚举,但我还不是 100%。

如果您尝试对超过列表长度的索引进行索引,您将遇到错误,但这可以通过向列表添加一个额外的元素来避免(在您的情况下它可以为零,因为您是在所有元素的总和之后):

def sum13(nums):
    nums += [0]
    for i in range(len(nums) - 1):
        if nums[i] == 13:
            nums[i] = 0
            nums[i + 1] = 0
    return sum(nums)

如果您想连续计算多个 13,请按相反的顺序进行:

    for i in reversed(range(len(nums) - 1)):
def sum13(nums):
    return (sum13(nums[2:]) if nums[0] == 13 else nums[0] + sum13(nums[1:])) if nums else 0

缺点是它不能连续处理多个 13。好处是它不会修改它的参数(一件好事)所以也可以处理只读数据。