根据特定值删除列表中的索引

时间:2018-11-27 20:25:32

标签: python list

我正在尝试解决以下问题:

返回数组中数字的总和,对于空数组返回0。除了13号是非常不幸的数字之外,因此它不会计数,紧接在13号之后的数字也不会计数。

这就是我的意思,这里的想法是删除13和1(紧随其后),然后将剩余的数字相加。我的问题是删除部分,实际上并没有删除任何内容。这是语法问题吗?

x = [1,2,2,1,13,1]

def sum13(nums):
    for i in nums:
        if i == 13:
            del nums[i:i+1]
    return sum(nums)

print(sum13(x))

20 <-- should be 6

4 个答案:

答案 0 :(得分:3)

您的问题出在索引上。 i是列表中的数字,而不是索引。 这是解决问题的一种方法:

x = [1,2,2,1,13,1]

def sum13(nums):
    for i, num in enumerate(nums):
        if num == 13:
            del nums[i:i+2] # This removes the index i and the index i+1
    return sum(nums)

print(sum13(x))
>>> 6

编辑: 正如Thierry Lathuille在评论中提到的那样,这并不能充分说明您重复'13'的情况。假设您想要这种行为,可以采用以下方法:

def sum13(nums):
    for i, num in enumerate(nums):
        if num == 13:
            stop_cut = i + 1     
            while nums[stop_cut] == 13:
                stop_cut += 1
            del nums[i:stop_cut+1]
    return sum(nums)

答案 1 :(得分:1)

只要您遍历该列表,只需保留一个连续的总和并记录上一个值。如果chars不是i,而前一个不是13,则添加到总和中,无需修改传入的列表。

13

答案 2 :(得分:1)

这里是带有循环功能的示例。只要列表中有13,我们就将其之前的所有内容和sum13之后的所有内容13相加。

x = [1,2,2,1,13,1]

def sum13(nums, first_call=False):
    if not first_call and nums[0] != 13:
        nums = nums[1:]
    if 13 in nums:
        return sum(nums[:nums.index(13)]) + sum13(nums[nums.index(13)+1:])
    return sum(nums)

print(sum13(x, True)) # -> 6

请注意,此解决方案适用于相邻的13

x = [13, 13, 1]
print(sum13(x, True)) # -> 0

答案 3 :(得分:1)

一个问题是您将列表元素值用作索引。这是使用发电机的解决方案。首先确定要忽略的值的索引,然后创建一个排除这些值的新列表。

x = [1,2,2,1,13,1]

def sum13(nums):

    def filter13(nums):
        for n, i in enumerate(nums):
             if i == 13:
                  yield n
                  yield n + 1

    bad_ix = set(filter13(nums))
    new_nums = [x for n, x in enumerate(nums) if n not in bad_ix]
    return sum(new_nums)

sum13(x)