使用索引i汇总数据

时间:2013-11-18 22:50:33

标签: python python-2.7

代码:

for i, words in enumerate(list):
    syn = eachscore(num)
    for score in syn:
        count = count + 1
        sscore = str(score).split()
        first = sscore[2]
        second = sscore[4]
        sumf = float(sumf) + float(first)
        sums = float(sumd) + float(second)
    print i, words, sumf, sums

结果显示:

0   A1  10  0
0   B1  2   27
1   B3  0   7
0   C1  1   10
1   C2  5   5
0   D1  10  1
1   D2  31  20
2   D5  20  10

我正在尝试对数据进行分组。

有人可以建议使用索引“i”对数据求和的方法吗?请...

期待结果:

A1  10  0
B1 B3   2   34
C1 C2   6   15
D1 D2 D5    61  31

2 个答案:

答案 0 :(得分:0)

也许是这样的?我根本没有测试它,但我相信它应该是接近的。

#!/usr/local/cpython-2.7/bin/python

def subresult():
    for i, words in enumerate(list):
        syn = eachscore(num)
        for score in syn:
            count = count + 1
            sscore = str(score).split()
            first = sscore[2]
            second = sscore[4]
            sumf = float(sumf) + float(first)
            sums = float(sumd) + float(second)
        # changed your print to a yield
        yield (words, sumf, sums)

def process():
    # untested
    dict_ = {}
    for words, sumf, sums in subresult():
        if words in dict_:
            dict_[words][0] += sumf
            dict_[words][1] += sums
        else:
            dict_[words] = [ sumf, sums ]
    return dict_

def main():
    dict_ = process():
    for key, value in dict_.items():
        print key, value

答案 1 :(得分:0)

好吧,试试吧。由于您没有包含任何示例输入或eachscore()方法,因此我无法验证这是否有效。此外,您在问题中发布的输出不能源自您提供的代码示例,因此我做了一些猜测。

import re
results = dict()

for words in list:
    syn = eachscore(num)

    # Results should be sorted by letters, e.g  get 'A' from the string 'A01'.
    # If this letter is case-insensitive, add .lower() to the expression
    key = re.sub('[0-9]*', '', words)

    # Try to append <words> to the dictonary item with key <key>.
    # If this fails, add a new entry (e.g. this is the first occurence of the letter)    
    try:
        results[key]['keys'].append(words)
    except KeyError:
        results[key] = {'keys': [words], 'sumf': 0, 'sums': 0}

    for score in syn:
        sscore = str(score).split()
        results[key]['sumf'] += float(sscore[2])
        results[key]['sums'] += float(sscore[4])

print results.items()