Skip to main content
 首页 » 编程设计

python之求和python列表中的整数但不包括数字13和紧随其后的数字

2025年05月04日14soundcode

我怎样才能做出比现有功能更好的功能?

def sum13(nums): 
    total = 0 
    wheresNumAfter13 = nums.index(13) + 1 
    numAfter13Value = nums[wheresNumAfter13] 
    for num in nums: 
        if num != 13: 
            total += num 
    return total - numAfter13Value 
 
print(sum13([1,2,3,4,5,13,4])) 

请您参考如下方法:

您可以对相关切片求和,类似于您正在做的,查找索引 13,然后对它之前和下一个元素之后的列表部分求和到 13。

您还可以对合并两部分的结果列表使用内置的sum 函数:

def sum13(nums): 
    wheres13 = nums.index(13) 
    return sum(nums[0:wheres13]+nums[wheres13+2:]) 

请注意,此解决方案与您的解决方案一样,仅适用于列表中只有 13 要排除的情况。
如果列表不包含 13,它们也会失败。


说明,例如列表示例:[1,2,3,4,5,13,​​4,10]:

  • 寻找 13:wheres13 = nums.index(13)
  • 获取列表中索引为 13 之前的部分:nums[0:wheres13]。这会生成一个类似 [1,2,3,4,5] 的列表,即从索引 0 到索引 wheres13(不包括它)。
  • 获取列表中 13 之后的部分:nums[wheres13+2:]。这会生成一个类似于 [10] 的列表,即从 13 之后的数字(其索引为 wheres13 加 2)到列表末尾.
  • 加入两个列表:nums[0:wheres13]+nums[wheres13+2:]。这会生成类似 [1,2,3,4,5,10]
  • 的列表
  • 对上一点的列表使用 python 的内置函数 sum

为了完整起见,这里修改为删除 every 13 和下一个数字的版本:

def sum13(nums): 
    n=nums 
    while 13 in n: 
        wheres13 = n.index(13) 
        n = n[0:wheres13]+n[wheres13+2:] 
    return sum(n)