Python - 以对齐的列打印CSV字符串列表 [英] Python - Print list of CSV strings in aligned columns

查看:1416
本文介绍了Python - 以对齐的列打印CSV字符串列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一段完全兼容 Python 2 Python 3 的代码片段。我写入的片段解析数据,它会将输出作为CSV字符串列表



此脚本提供选项




  • 将数据写入 CSV文件

  • 显示到 stdout



虽然我可以轻松地遍历列表并替换 c $ c> \t 当显示到 stdout (第二个项目符号选项)时,项目是任意长度,因此不排队在一个很好的格式,由于标签中的差异。



我做了相当多的研究,我相信字符串格式选项可以完成我的后。



我更喜欢不使用外部库。我知道有很多选项可用,如果我走这条路线,但我希望脚本尽可能兼容和简单。



这里是一个例子: / p>

  value1,somevalue2,value3,reallylongvalue4,value5,superlongvalue6 
value1,value2,reallylongvalue3,value4,value5,somevalue6

你能帮我吗?任何建议都将非常感激。

解决方案

  import csv 
从StringIO import StringIO

rows = list(csv.reader(StringIO(
'''value1,somevalue2,value3,reallylongvalue4,value5,superlongvalue6
value1,value2,reallylongvalue3,value4,value5 ,somevalue6''')))

wides = [max(len(row [i])for row in rows)for i in range(len(rows [0]))]

行中的行:
print('|'.join(cell.ljust(width)for cell,width in zip(row,width)))



输出:

  value1 | somevalue2 | value3 | reallylongvalue4 | value5 | superlongvalue6 
value1 | value2 | reallylongvalue3 | value4 | value5 | somevalue6


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.

The script provides an option to:

  • write the data to a CSV file, or
  • display it to the stdout.

While I could easily iterate through the list and replace , with \t 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.

Here is an example:

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)))

Output:

value1 | somevalue2 | value3           | reallylongvalue4 | value5 | superlongvalue6
value1 | value2     | reallylongvalue3 | value4           | value5 | somevalue6     

这篇关于Python - 以对齐的列打印CSV字符串列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆