Python - Print list of CSV strings in aligned columns(Python - 在对齐的列中打印 CSV 字符串列表)
问题描述
我编写了一个完全兼容 Python 2 和 Python 3 的代码片段.我编写的片段解析数据并将输出构建为 CSV 字符串列表.
I have written a fragment of code that is fully compatible with both Python 2 and Python 3. The fragment that I wrote parses data and it builds the output as a list of CSV strings.
脚本提供了一个选项来:
- 将数据写入
CSV 文件,或 - 将其显示到
stdout.
虽然在显示到 stdout(第二个项目符号选项)时,我可以轻松地遍历列表并将 , 替换为 ,但这些项目长度是任意的,因此由于制表符的差异,请不要以很好的格式排列.
While I could easily iterate through the list and replace , with when displaying to stdout (second bullet option), the items are of arbitrary length, so don't line up in a nice format due to variances in tabs.
我做了很多研究,我相信字符串格式选项可以完成我所追求的.也就是说,我似乎找不到可以帮助我正确使用语法的示例.
I have done quite a bit of research, and I believe that string format options could accomplish what I'm after. That said, I can't seem to find an example that helps me get the syntax correct.
我宁愿不使用外部库.我知道如果我走这条路有很多可用的选项,但我希望脚本尽可能兼容和简单.
I would prefer to not use an external library. I am aware that there are many options available if I went that route, but I want the script to be as compatible and simple as possible.
这是一个例子:
value1,somevalue2,value3,reallylongvalue4,value5,superlongvalue6
value1,value2,reallylongvalue3,value4,value5,somevalue6
你能帮帮我吗?任何建议将不胜感激.
Can you help me please? Any suggestion will be much appreciated.
推荐答案
import csv
from StringIO import StringIO
rows = list(csv.reader(StringIO(
'''value1,somevalue2,value3,reallylongvalue4,value5,superlongvalue6
value1,value2,reallylongvalue3,value4,value5,somevalue6''')))
widths = [max(len(row[i]) for row in rows) for i in range(len(rows[0]))]
for row in rows:
print(' | '.join(cell.ljust(width) for cell, width in zip(row, widths)))
输出:
value1 | somevalue2 | value3 | reallylongvalue4 | value5 | superlongvalue6
value1 | value2 | reallylongvalue3 | value4 | value5 | somevalue6
这篇关于Python - 在对齐的列中打印 CSV 字符串列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python - 在对齐的列中打印 CSV 字符串列表
基础教程推荐
- Discord.py 缺少必需的参数 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
