gpt4 book ai didi

python - 添加新行以在 python 中打印 csv 的列输出

转载 作者:太空宇宙 更新时间:2023-11-03 15:15:18 25 4
gpt4 key购买 nike

我对 python 相当陌生,正在尝试确定执行此操作的最佳方法。我有以下代码。

import csv
from collections import defaultdict
columns = defaultdict(list)

with open('test.csv') as f:
reader = csv.DictReader(f)
for row in reader:
for (k,v) in row.items():
columns[k].append(v)

print(columns['Created'])
print(columns['Person'])
print(columns['Comment'])

我正在针对以下 CSV 文件输出运行它。

Created,UnwantedData,Person,Bogus,Comment
4-15-17,test,Chad,w,There is an update
4-16-17,for,Marlon,x,There is no update
4-17-17,this ,Kevin,y,I have reviewed the files
4-18-17,issue,Dan,z,I hate this place.

我只想打印“已创建”、“人员”和“评论”部分,但我得到了以下内容。

['4-15-17', '4-16-17', '4-17-17', '4-18-17']
['Chad', 'Marlon', 'Kevin', 'Dan']]
['There is an update ', 'There is no update', 'I have reviewed the files ', 'I hate this place. ']

我试图通过在每次打印输出之间添加一个新行来使输出看起来像这样。

4-15-17   
Chad
There is an update

4-16-17
Marlon
There is no update

4-17-17
Kevin
I have reviewed the files

4-18-17
Dan
I hate this place.

任何事情都将不胜感激

最佳答案

我可以建议一种替代方法,您只需创建一个新的条目列表,然后将 dict 简单地过滤为仅包含所需的键。

import csv
wanted = ('Created', 'Person', 'Comment')

with open('test.csv') as f:
rdr = csv.DictReader(f)

result = []
for row in rdr:
result.append({k: v for k, v in row.items() if k in wanted})

for r in result:
print(r['Created'])
print(r['Person'])
print(r['Comment'])
print('')

如果您想使用现有代码,只需使用 zip 重新加入每个列表中的项目即可。

import csv
from collections import defaultdict
columns = defaultdict(list)

with open('test.csv') as f:
reader = csv.DictReader(f)
for row in reader:
for k, v in row.items():
columns[k].append(v)

params = [columns['Created'], columns['Person'], columns['Comment']]
for cre, pers, cmt in zip(*params):
print(cre)
print(pers)
print(cmt)
print('')

关于python - 添加新行以在 python 中打印 csv 的列输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43928882/

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