增加基本值python for循环

时间:2013-05-17 07:16:06

标签: python for-loop increment

每次在for循环中循环“i”时,如何递增基值? 逻辑是这样的:

fruits = [bananas, apples, pears]
total_fruits_count = 0

for i in fruits:
    ## some code resolveing fruit count ##
    local_fruit_count = 1
    total_fruits_count + local_fruit_count

print total_fruits_count

使用此代码,total_fruits_count最终为0.这怎么可能?

3 个答案:

答案 0 :(得分:0)

您需要修改total_fruits_count

的值
fruits = ["bananas", "apples", "pears"]
total_fruits_count = 0

for i in fruits:
    local_fruit_count = 1
    total_fruits_count += local_fruit_count

print total_fruits_count

在您的原始代码中,您执行了total_fruits_count + local_fruit_count,它计算了两者的总和,但没有对它做任何事情。加号等于快捷键+=会添加值并将其存储在左侧变量total_fruits_count中。

答案 1 :(得分:0)

这只计算总和并丢弃结果

total_fruits_count + local_fruit_count

您需要=将结果分配回total_fruits_count

total_fruits_count += local_fruit_count

答案 2 :(得分:0)

我认为您可以根据需要使用枚举函数或len

fruits = ["bananas", "apples", "pears"]
for i, fruit in enumerate(fruits):
     print "fruit with index %d is '%s'" % (i, fruit)

total_fruits_count = len(fruits)