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