繁体   English   中英

使用OrderedDict以相反的顺序从CSV文件输出列表

[英]Using OrderedDict to output list in reverse order from CSV file

我需要导入一个包含以下内容的CSV文件:

name,mean performance,std dev
Alice,100,0
Bob,100,5 
Clare,100,10
Dennis,90,0
Eva,90,5

并将输出结果排序为:

{'Dennis': (90.0, 0.0), 'Clare': (100.0, 10.0), 'Eva': (90, 5.0), 'Bob': (100.0, 5.0), 'Alice': (100.0, 0.0)}

到目前为止,我有:

import csv
import collections

def sailorPerf(filename, header=True):

    with open(filename, mode='r') as csvfile:
        r = csv.reader(csvfile)
        if header==True:
            next(r)
        od = collections.OrderedDict((row[0], row[1]) for row in r)
    print (od)

哪个输出:

OrderedDict([('Alice', ' 100'), ('Bob', ' 100'), ('Clare', ' 100'), ('Dennis', ' 90'), ('Eva', ' 90')])

我想知道如何将第三列添加到结果中,以及如何更改格式以将ordereddict部分从输出中删除,以及如何更改输出的命名方式并使其具有预期结果中的名称和输出。

(row[0], row[1])更改为(row[0], tuple(row[1:]))以将第二个作为包含来自索引1的所有元素的列表-列表结尾,然后将其强制转换为元组。

您需要通过将第二和第三列转换为int来对数据进行排序:

from collections import OrderedDict
def sailorPerf(filename, header=True):
    with open(filename, mode='r') as csvfile:
        r = csv.reader(csvfile)
        if header:
            next(r)
        od = OrderedDict((name, tuple(rest)) 
                  for name,*rest in sorted(r, key=lambda x: (int(x[1]), int(x[2]))))
        return od


print(sailorPerf("test.txt"))

输出:

OrderedDict([('Dennis', ('90', '0')), ('Eva', ('90', '5')),
        ('Alice', ('100', '0')), ('Bob', ('100', '5')),
        ('Clare', ('100', '10'))])

如果您真的不想看到OrderedDict,可以致电list(od.items)

print(list(sailorPerf("test.txt").items()))

OrderedDict([('Dennis', ('90', '0')), ('Eva', ('90', '5')), 
          ('Alice', ('100', '0')), ('Bob', ('100', '5')),
                 ('Clare', ('100', '10'))])

对于python2,只需解压缩即可:

def sailorPerf(filename, header=True):
    with open(filename, mode='r') as csvfile:
        r = csv.reader(csvfile)
        if header==True:
            next(r)
        od = OrderedDict((nm, (mn, std))) 
                  for nm, mn, std in sorted(r,key=lambda x: (int(x[1]),int(x[2]))))
        return od

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM