【问题标题】:Python: Nested If LoopingPython:嵌套 If 循环
【发布时间】:2012-08-14 08:59:48
【问题描述】:

这让我很生气 :) 我正在尝试根据月份从列表中求和值,我尝试了一些事情,但非常需要指导。

我正在尝试: 第 1 - 12 个月。

从列表 (EC_PlanData) 中迭代读取 PlanWeek(4) 值,然后求和

然后根据求和值计算平滑平均值。

这是我的代码:

G_counter = 1
j = i
m = 1
Plantotal = 0
PlanMonth = 0
DFD = []
EC_PlanData = [500,500.... etc] # 52 values

PlanWeek = range(j,j+3)
Month = range(m,13,1)

## Define Variables
ym, xh, xm, N1, Z1, N2, Z2 = 0,0,0,0,0,0,0

for month in Month:      # for each month 1 - 13
    for i,e in enumerate(list_1):      # read through list
        PlanMonth = PlanMonth + i+3    # sum 4 weekly values
        DFD.append(PlanMonth)          # append sum value to DFD list
        if i == 1:                     # if G_counter = 1, which it always is
            IFX.append(PlanMonth)      # also append to IFX list

    Plantotal= Plantotal+PlanMonth     # calculations here on are
    for i,e in enumerate(DFD):         # evaluated after appending above
        y = e

    ym = Plantotal / m                 # These are calculating a smoothing average
    xh = xh + m
    xm = xh / m      
    N1 = (m-xm) * (y-ym)
    Z1 = (m-xm) * (m-xm)
    N2 = N2 + N1
    Z2 = Z2 + Z1

    if Z2 == 0:                        # Decision on FC value
        FC = 0                         # This or
    else:
        FC = ym -(N2/Z2)*xm + (N2/Z2)*(m+1) # This

    J +=4                              # Advances on 4 time periods
    M +=1                              # Advances on 1 Month
    PlanMonth = 0                      # Resets PlanMonth variable

【问题讨论】:

  • PlanMonth 最初来自哪里?我希望你没有真的在那个列表中写了 500 52 次, list_2 和 list_3 在哪里?究竟是什么问题?计划周有什么用?
  • 不清楚您要达到的目标。建议用伪代码描述问题
  • 你能指定你的任务吗?您是否只需要对给定月份的第三个列表元素求和?
  • 第 1 个月的 PlanMonth 是从 1 到 4 的值的总和。第 2 个月的 PlanMonth 是从 5 到 8 等值的总和因此 list2list3变成 13 个相加值。 i hope you didnt really write 500 52 times in that list .. 不,这是自动生成的,但出于验证目的,我将数字固定为 500。
  • @manangstudent 请通过单击edit 链接更新您的答案,并重新编写它以使其更清晰并回答 cmets 中的问题。还要确保示例代码可以作为独立脚本运行而不会引发异常。

标签: python loops if-statement


【解决方案1】:

您必须意识到 12 不能除以 52,并且每个月都没有 4 周。所以举一个例子,你可以微调以获得你想要的东西,我已经定义了一周属于它的星期四所属的同一个月。这与 ISO 8601 对一年中第一周的定义非常吻合。如果还剩一周,那么我将那一周添加到 12 月。

import datetime
from itertools import groupby

def get_week(date):
    return date.isocalendar()[1]

def group_by_month(weeks, year):
    """
    Group a list containing one item per week, starting with week 1, by month.

    If there are too few items to fill a year, stop after last item.
    If there are more items than weeks in the year, stop before new year.
    """
    day = datetime.timedelta(days=1)
    week = datetime.timedelta(days=7)

    # Find first Thursday (it's in week 1 by ISO 8601)
    date = datetime.date(year, 1, 1)
    while date.weekday() != 3:
        date += day

    # Create list of one day from each week
    thursdays = []
    while date.year == year:
        thursdays.append(date)
        date += week

    # Check if the last day is in the last week and if not, 
    # add the week of the last day
    last = tursdays[-1]
    if get_week(last.replace(day=31)) != get_week(last):
        # this will not be a Thursday, but what the hey
        thursdays.append(last.replace(day=31))

    # The thursdays are already sorted by month, so 
    # it's OK to use groupby without sorting first
    for k, g in groupby(zip(weeks, thursdays), key=lambda x: x[1].month):
        yield [x[0] for x in g]

list_1 = [500] * 52

print map(sum, group_by_month(list_1, 2012))

结果:

[2000, 2000, 2500, 2000, 2500, 2000, 2000, 2500, 2000, 2000, 2500, 2000]

您还应该注意,年份可能包含 53 weeks,如果是这样,您必须提供 53 项列表而不是 52 项列表。如果不这样做,第 53 周就会被忽略。

【讨论】:

  • 哦,哇,太棒了,从初学者程序员的角度来看,我还有很多东西要学。但这确实有效。在我看到这个之前,我已经转发了我原来的帖子。至于 53 周的情况,我知道它,多年使用 Excel ;),但你一举解决了这个问题。我会看看我是否可以处理您提供的内容以继续平滑平均部分。顺便说一句,答案很好。
  • @manengstudent 为了方便与其他 python 编码人员的交流,我建议您查看the python style guide。符合(几乎)每个人都知道和遵循的风格的代码更容易阅读,对于 python,就是这样。
猜你喜欢
  • 1970-01-01
  • 2016-10-30
  • 2010-12-21
  • 2017-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-15
  • 2015-10-01
相关资源
最近更新 更多