3

我有一个包含内容的 .csv 文件(示例)

Attributes,Description,Dial-Up
4,2,0.2
3,1,0.4

使用字典阅读器:

dictreader = csv.DictReader(open(filename, "rb"), delimiter=',')
dictdata = {}
count=0
for row in dictreader:
    dictdata[count]=row
    count=count+1

并显示在表格中或使用作家我会得到:

Dial-Up,Attributes,Description
0.2,4,2
0.4,3,1

那么如何对字段名进行排序呢?

4

1 回答 1

10

DictReader字段(dict 键)存储在名为的属性中fieldnames

fields = dictreader.fieldnames
print(fields)
# ['Attributes', 'Description', 'Dial-Up']

因此,要按此顺序打印行值:

print(','.join(fields))
for row in dictreader:
    print(','.join(row[field] for field in fields))

产量

Attributes,Description,Dial-Up
4,2,0.2
3,1,0.4

或者,使用@JonClements 的想法:

import operator
fields = dictreader.fieldnames
getfields = operator.itemgetter(*fields)
for row in dictreader:
    print(','.join(getfields(row)))

使用的动机operator.itemgetter是它比使用列表理解更快:

In [70]: %timeit getfields(row)
10000000 loops, best of 3: 174 ns per loop

In [71]: %timeit [row[field] for field in fields]
1000000 loops, best of 3: 272 ns per loop
于 2013-01-14T12:28:25.710 回答