如何按顺序获得此输出?

时间:2015-08-25 04:02:02

标签: python excel xlrd

import xlrd
import sys

from collections import defaultdict
out = defaultdict(list)

workbook = xlrd.open_workbook('Dummy Input Data.xlsx')
worksheet = workbook.sheet_by_index(0)
headers = worksheet.row(0)
result = []
for index in range(worksheet.nrows)[1:]:
    result.append(worksheet.row(index)[0].value)
for uniq in set(result):
    sum = 0
    for index in range(worksheet.nrows)[1:]:
       if uniq == worksheet.row(index)[0].value:
            sum = sum + worksheet.row(index)[4].value
    out[uniq] = int(sum)
for rec in out:
    print rec+" "+str(out[rec])

I got output like this:
Engineer-2 16
Engineer-3 19
Engineer-1 11
Engineer-4 24
Engineer-5 12

如何对名称和数字进行排序,我需要按顺序结果:

Engineer-1 11

Engineer-2 16

Engineer-3 19

Engineer-4 24

Engineer-5 12

如何获得如上所述的结果,它应该从1,2,3,4,5开始...但我得到的输出不是按顺序。

2 个答案:

答案 0 :(得分:1)

试试这个:

for rec in sorted(out.keys()):
    print rec+" "+str(out[rec])

样本:

>>> a
{'Engineer-2': 16, 'Engineer-3': 19, 'Engineer-1': 11, 'Engineer-4': 24, 'Engineer-5': 12}
>>> for k in sorted(a.keys()):
...     print k, a[k]
... 
Engineer-1 11
Engineer-2 16
Engineer-3 19
Engineer-4 24
Engineer-5 12

答案 1 :(得分:0)

你使用两种不同的数据结构,没有任何顺序感 - 字典和集合 - 所以得到的结果不同于原始顺序(excel中存在的顺序)不应该是惊人的

如果你想要的是使用name中的1-5订购结果,那么你可以在sorted()上使用out.keys(),例如 -

for rec in sorted(out.keys()):
    print rec+" "+str(out[rec])

如果您的真实意图是以原始格式恢复数据,它存在于excel中,那么您不应该为uniq元素创建一个集合,而是使用另一个元素创建result作为唯一元素的列表设置为存储已经看到的元素。示例 -

seen = set()
result = []
for index in range(worksheet.nrows)[1:]:
    e = worksheet.row(index)[0].value
    if e not in seen:
        seen.add(e)
        result.append(e)

然后使用result列表迭代字典以打印值。示例 -

for rec in result:
    print rec+" "+str(out[rec])