gpt4 book ai didi

Python Dictreader 排序字段名

转载 作者:行者123 更新时间:2023-11-28 20:49:29 26 4
gpt4 key购买 nike

我有一个包含内容(示例)的 .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

并显示在表格中或使用 writer 我将得到:

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

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

最佳答案

DictReader 将字段(字典键)存储在名为 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

关于Python Dictreader 排序字段名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14317849/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com