如何计算特定周数之间的周数?

时间:2013-04-21 08:25:26

标签: python dictionary count

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

{'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)

任何人都可以帮我吗?

1 个答案:

答案 0 :(得分: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}
相关问题