Python 列表中除6和7之间的数字外的数字总和
我正在尝试编写一个函数,它接受一个列表并对列表中的所有数字求和,除了它忽略列表中以列表开始并扩展到7的部分,但在7之后继续求和。这是我的密码:Python 列表中除6和7之间的数字外的数字总和,python,indices,Python,Indices,我正在尝试编写一个函数,它接受一个列表并对列表中的所有数字求和,除了它忽略列表中以列表开始并扩展到7的部分,但在7之后继续求和。这是我的密码: def sum67(nums): i = 0 sum = 0 while i < len(nums): k = 0 if nums[i] != 0: sum += nums[i] i += 1 if nums[i] == 6: for j i
def sum67(nums):
i = 0
sum = 0
while i < len(nums):
k = 0
if nums[i] != 0:
sum += nums[i]
i += 1
if nums[i] == 6:
for j in range(i + 1, len(nums)):
if nums[j] != 7:
k += 1
if nums[j] == 7:
k += 2
i += k
`发布的代码完全被破坏。 例如,对于没有任何6的列表, 当在最后一个元素上达到
nums[i]==6
条件时,i
将超出列表范围
您需要完全重新考虑循环中的条件。
这里有一个可行的方法。
如果当前的数字是6,
然后跳过,直到你看到一个7,不加总。
否则,加在总数上。
在执行这两个操作(跳过数字或相加)中的任何一个之后,
增量i
def sum67(nums):
i = 0
total = 0
while i < len(nums):
if nums[i] == 6:
for i in range(i + 1, len(nums)):
if nums[i] == 7:
break
else:
total += nums[i]
i += 1
return total
def sum67(nums):
i=0
总数=0
而我
以下是学习新Python技术的中间选择:
import itertools as it
def span_sum(iterable, start=6, end=7):
"""Return the sum of values found between start and end integers."""
iterable = iter(iterable)
flag = [True]
result = []
while flag:
result.extend(list(it.takewhile(lambda x: x!=start, iterable)))
flag = list(it.dropwhile(lambda x: x!=end, iterable))
iterable = iter(flag)
next(iterable, [])
return sum(result)
# Tests
f = span_sum
assert f([1, 2, 2]) == 5
assert f([1, 2, 2, 6, 99, 99, 7] ) == 5
assert f([1, 6, 2, 2, 7, 1, 6, 99, 99, 7]) == 2
assert f([1, 6, 2, 6, 2, 7, 1, 6, 99, 99, 7]) == 2
assert f([2, 7, 6, 2, 6, 7, 2, 7]) == 18
原则上,此函数过滤输入,将值收集到满足条件的结果中,并删除其余值,然后返回总和。特别是,您可以观察以下技术:
import itertools as it
def span_sum(iterable, start=6, end=7):
"""Return the sum of values found between start and end integers."""
iterable = iter(iterable)
flag = [True]
result = []
while flag:
result.extend(list(it.takewhile(lambda x: x!=start, iterable)))
flag = list(it.dropwhile(lambda x: x!=end, iterable))
iterable = iter(flag)
next(iterable, [])
return sum(result)
# Tests
f = span_sum
assert f([1, 2, 2]) == 5
assert f([1, 2, 2, 6, 99, 99, 7] ) == 5
assert f([1, 6, 2, 2, 7, 1, 6, 99, 99, 7]) == 2
assert f([1, 6, 2, 6, 2, 7, 1, 6, 99, 99, 7]) == 2
assert f([2, 7, 6, 2, 6, 7, 2, 7]) == 18
- 单子
- ,例如,
itertools.takewhile
,itertools.dropwhile
- 函数和默认值
- 作用
正确的测试是n==6
,而不是n是6
。这是一个依赖于实现的细节,它适用于小整数。
import itertools as it
def span_sum(iterable, start=6, end=7):
"""Return the sum of values found between start and end integers."""
iterable = iter(iterable)
flag = [True]
result = []
while flag:
result.extend(list(it.takewhile(lambda x: x!=start, iterable)))
flag = list(it.dropwhile(lambda x: x!=end, iterable))
iterable = iter(flag)
next(iterable, [])
return sum(result)
# Tests
f = span_sum
assert f([1, 2, 2]) == 5
assert f([1, 2, 2, 6, 99, 99, 7] ) == 5
assert f([1, 6, 2, 2, 7, 1, 6, 99, 99, 7]) == 2
assert f([1, 6, 2, 6, 2, 7, 1, 6, 99, 99, 7]) == 2
assert f([2, 7, 6, 2, 6, 7, 2, 7]) == 18