说我有一个数字列表:
foo = [random.randint(0, 9) for n in range(10)]
我有一个功能
def bar(lst):
total = 0
for i in lst:
total += i
if total % 4 == 0:
print "passed multiple of 4"
bar(foo)
如果total
跳过4的倍数,如何让print语句执行?
编辑:说foo = [4,5]
,然后total
获取值0
,4
和9
。我希望print语句执行两次,一次用于4
,一次用于8
,其中total
"跳过"当它从4跳到9时。
答案 0 :(得分:1)
我希望print语句执行两次,一次执行4次,执行一次,一次执行8次,总共"跳过"当它从4跳到9时。
所以基本上,你不想检查模数,而只是检查总数是否超过4的倍数。
这样的事情:
def bar(lst):
total = 0
# keep track of the numbers we need to “pass” to print the notice; the first one is 4
passed = 4
for i in lst:
total += i
# when the total passed the number
while total >= passed:
# print the notice
print('passed multiple of 4, total is {0}'.format(total))
# and skip to the next number
passed += 4
>>> bar([4, 5])
passed multiple of 4, total is 4
passed multiple of 4, total is 9
>>> bar([1, 3, 4])
passed multiple of 4, total is 4
passed multiple of 4, total is 8
>>> bar([1, 12])
passed multiple of 4, total is 13
passed multiple of 4, total is 13
passed multiple of 4, total is 13