【发布时间】:2016-03-04 03:49:30
【问题描述】:
我有一个在给定列表中搜索数字 13 的脚本。如果找到 13,则需要将其删除,但我还需要删除它之后的索引。我找到了所有的 13 并将它们删除,但我不确定删除它之后的索引的最佳方法。我知道我需要先在 13 之后删除索引,因为删除后会发生变化。最后我需要返回我所做的所有索引的总和。
这是我在 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%那些还没有。
【问题讨论】:
-
连续多个 13 的预期行为是什么?
-
可能相关:您可能想使用for with reversed order to do this safely。
-
如果到了list的最后,就去掉所有的13s,如果多个13s之后还有什么,那就是下一个要删除的索引。