用于python中的循环索引
我的for循环有什么问题?我遇到了与数组索引相关的问题 如何修复for循环中的索引问题? “对于月销售额: 季度+=销售额“” 创建月份列表和索引,并将季度设置为0用于python中的循环索引,python,for-loop,indexing,Python,For Loop,Indexing,我的for循环有什么问题?我遇到了与数组索引相关的问题 如何修复for循环中的索引问题? “对于月销售额: 季度+=销售额“” 创建月份列表和索引,并将季度设置为0 months = [100, 100, 150, 250 , 300, 10, 20] quarter = 0 quarters = [] index = 0 为季度创建for循环,打印结果,并增加索引 for sales in months: quarter += sales if index % 3 == 0 or
months = [100, 100, 150, 250 , 300, 10, 20]
quarter = 0
quarters = []
index = 0
为季度创建for循环,打印结果,并增加索引
for sales in months:
quarter += sales
if index % 3 == 0 or index == len(months):
quarters.append(quarter)
quarter = 0
index = index + 1
print("The quarter totals are Q1: {}, Q2: {}, Q3: {}".format(quarters[0], quarters[1], quarters[2]))
看起来您复制了一些缩进错误,但我猜在代码中,
index=index+1
缩进到if块中,因此它将停止递增。您可以使用enumerate
来完全避免此类错误
for index, value in enumerate(collection):
print(index, value) # your code here
试试这个:
# Month sales data
month_sales = [100, 100, 150, 250, 300, 10, 20]
# Empty list to hold quarter data
quarter_sales = []
# Current quarter iteration data
quarter = 0
# Iterate over monthly sales
for index, sale in enumerate(month_sales):
# Add month's sales to running total for the quarter
quarter += sale
# If last month of quarter or end of list
if (index + 1) % 3 == 0 or index == len(month_sales) - 1:
# Add quarter sales data to new list and start over
quarter_sales.append(quarter)
quarter = 0
print(f"The quarter totals are Q1: {quarter_sales[0]}, Q2: {quarter_sales[2]}, Q3: {quarter_sales[2]}")
你的索引有问题
例如,如果索引开始于
1
,则索引%3
将起作用,但在编程列表中,索引开始于0
。这相当于第3个月处于指数2。因为2不能被3整除,所以它会继续前进,将前四个月抛到第1季度,以此类推。您需要修改您的代码以说明这一点,使用(索引+1)%3==0
和len(月销售)-1
您的问题是什么?请澄清。如果需要建议,请查看。索引有什么问题?如果出现错误,请完整提供。请参阅以供参考。