【问题标题】:How to count the weeks between specific week numbers?如何计算特定周数之间的周数?
【发布时间】:2013-04-21 08:25:25
【问题描述】:

我有以下数据格式。它是一个以名称为键,以周数列表为值的字典。

{'Mali': [17, 16, 23, 18, 17, 16, 17, 18, 16],
 'Gooki': [7, 8, 8, 15, 7, 7, 8],
 'Piata': [85],     
 'Goerge': [82],
 'Samoo': [106, 55],
 'Marria: [101,39]}

我想计算周数之间的周数,并用周数而不是周数更改字典的值。这意味着例如在名称“Samoo”中,我有第 55 周和第 106 周. 我希望我的代码计算这两周加上它们之间的周数(等于 52 周)并将其设置为字典的值。

我有下面的代码,但我不确定是否能将其计算在内。

datedict = defaultdict(set)
with open('d:/info.csv', 'r') as csvfile:
    filereader = csv.reader(csvfile, 'excel')

    #passing the header
    read_header = False
    start_date=date(year=2009,month=1,day=1)
    #print((seen_date - start_date).days)
    tdict = {}
    for row in filereader: 
        if not read_header:
            read_header = True
            continue

# reading the rest rows
        name,firstseen = row[0],row[3]
        try:
            seen_date = datetime.datetime.strptime(firstseen, '%d/%m/%Y').date()               
            deltadays = (seen_date-start_date).days
            deltaweeks = deltadays/7 + 1
            key = name
            currentvalue = tdict.get(key, set())
            currentvalue.add(deltaweeks)
            tdict[key] = currentvalue

        except ValueError:
            print('Date value error')
            pass

pprint.pprint(tdict)

谁能帮我解决这个问题?

【问题讨论】:

  • 您的字典中有两次Samoo。这是故意的吗?另外,106-55 不等于51 吗?对不起,我可能误解了你的问题
  • @Haidro 我想他也想算上第 106 周,所以那就是+1
  • @jamylak 啊,这似乎是合理的。其实我觉得你是对的。看这一行:deltaweeks = deltadays/7 + 1
  • 能否请您回答:'Mali'
  • 马里有 16 到 23 之间

标签: python dictionary count


【解决方案1】:
>>> d = {'Mali': [17, 16, 23, 18, 17, 16, 17, 18, 16],
 'Gooki': [7, 8, 8, 15, 7, 7, 8],
 'Piata': [85],
 'Samoo': [47, 63, 48, 58, 49, 48],
 'Goerge': [82],
 'Samoo': [106, 55],
 'Marria': [101,39]}
>>> dict((name, max(weeks) - min(weeks) + 1) for name, weeks in d.iteritems())
{'Samoo': 52, 'Gooki': 9, 'Mali': 8, 'Goerge': 1, 'Piata': 1, 'Marria': 63}

【讨论】:

  • @user2058811 dict 不是变量,而是函数。你也没有发布错误
  • @user2058811 您必须调用了隐藏内置函数的变量之一dict,检查您的代码中是否存在任何名为dict 的变量并更改它们的名称。这个 sn-p: dict = __builtins__.dict 应该为你重置它
  • @user2058811 像这样:>>> dict <type 'dict'>,没关系
  • @user2058811 是的,这是应该发生的,它是一个函数(它打印 type,因为它是用 C 语言制作的)。现在尝试运行代码:dict((name, max(weeks) - min(weeks) + 1) for name, weeks in d.iteritems())
猜你喜欢
  • 2021-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-08
  • 1970-01-01
  • 2023-04-10
相关资源
最近更新 更多