使用索引i总结数据

2024-04-19 07:03:22 发布

您现在位置:Python中文网/ 问答频道 /正文

代码:

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

Tags: infora1countfloatb1b3first
2条回答

好吧,试试这个。因为您没有包含任何示例输入或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()

也许是这样的?我根本没试过,但我相信应该很接近。你知道吗

#!/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

相关问题 更多 >