1

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

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

谁能帮我这个?

4

1 回答 1

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}
于 2013-04-21T08:34:39.463 回答