用例很简单。我有一个不同长度的字符串列表,我想打印它们,以便以表格的形式显示它们(见下文)。请考虑在计算机上列出一个目录。它将它们显示为符合当前窗口大小的表,并考虑到列表中最长的值,以便对齐所有列。为了满足我的需要,我会在需要包装之前指定最大行长。
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。它工作的系统使用python 3.6.4。我需要在一个使用2.6.6版本的系统上这样做。当我在这个系统上尝试我的代码时,我得到以下错误:
$ python test.py . 80
Traceback (most recent call last):
File "test.py", line 46, in <module>
main()
File "test.py", line 43, in main
printTable(dirList, maxLen)
File "test.py", line 27, in printTable
printList.append(formatStr.format(item))
ValueError: zero length field name in format我假设我用来构建格式说明符的技术就是它所抱怨的。
以下是逻辑:
注意事项:我只是通过获取目录列表来生成本例中的列表。我的实际用例不使用目录列表。
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 <directory> <max length>" % (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 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发布于 2018-09-11 12:43:39
for item in subList:
formatStr = '{:%d}' % (itemMax)
printList.append(formatStr.format(item))根据ValueError: zero length field name in format in Python2.6.6的说法,您不能在2.6.6中使用“匿名”格式字符串。像"{:10}"这样的语法直到2.7才成为合法。在此之前,您需要提供一个显式索引,比如"{0:10}"。
for item in subList:
formatStr = '{0:%d}' % (itemMax)
printList.append(formatStr.format(item))..。但是,我觉得跳过所有这些并使用ljust可以省去一些麻烦。
for item in subList:
printList.append(str(item).ljust(itemMax))https://stackoverflow.com/questions/52276126
复制相似问题