python打印表格对齐 python2,Python2.6.6如何以表格形式打印列对齐的列表?

这个用例很简单。我有一个不同长度的字符串列表,我想把它们打印出来,以便以表格形式显示(见下文)。考虑在你的计算机上列出一个目录。它将它们显示为适合当前窗口大小的表,并考虑列表中最长的值,以便所有列都对齐。根据我的需要,我会在需要换行之前指定最大行长度。在config constants.py fuzzer

fuzzer_session generator.py README.docx

run_fuzzer_session.py run_generator.py tools

util VM_Notes.docx wire_format_discoverer

xml_processor

我想出了一种方法来实现这一点,但显然它只适用于更新版本的python。它工作的系统使用的是python3.6.4。我需要在使用版本2.6.6的系统上执行此操作。当我在这个系统上尝试我的代码时,我得到了以下错误:

^{pr2}$

我假设我用来构建格式说明符的技术就是它所抱怨的。在

逻辑如下:

注意:在本例中,我通过获取目录列表来生成列表。我的实际用例不使用目录列表。在import os

import sys

def printTable(aList, maxWidth):

if len(aList) == 0:

return

itemMax = 0

for item in aList:

if len(item) > itemMax:

itemMax = len(item)

if maxWidth > itemMax:

numCol = int(maxWidth / itemMax)

else:

numCol = 1

index = 0

while index < len(aList):

end = index + numCol

subList = aList[index:end]

printList = []

for item in subList:

formatStr = '{:%d}' % (itemMax)

printList.append(formatStr.format(item))

row = ' '.join(printList)

print(row)

index += numCol

def main():

if len(sys.argv) < 3:

print("Usage: %s " % (sys.argv[0]))

sys.exit(1)

aDir = sys.argv[1]

maxLen = int(sys.argv[2])

dirList = os.listdir(aDir)

printTable(dirList, maxLen)

if __name__ == "__main__":

main()

有没有一种方法可以实现我在Python2.6.6上要做的事情?在

我相信有更好的(更“Python”)的方法来完成这里执行的一些步骤。我做我知道的事。如果有人想提出更好的方法,欢迎发表意见。在

以下是成功运行的示例:>python test.py .. 80

config constants.py fuzzer

fuzzer_session generator.py README.docx

run_fuzzer_session.py run_generator.py tools

util VM_Notes.docx wire_format_discoverer

xml_processor

>python test.py .. 60

config constants.py

fuzzer fuzzer_session

generator.py README.docx

run_fuzzer_session.py run_generator.py

tools util

VM_Notes.docx wire_format_discoverer

xml_processor

>python test.py .. 120

config constants.py fuzzer fuzzer_session generator.py

README.docx run_fuzzer_session.py run_generator.py tools util

VM_Notes.docx wire_format_discoverer xml_processor

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值