这是我的三个列表:
# made up data
products = ['apple','banana','orange']
prices = ['£0.11','£0.07','£0.05']
dates = ['02/04/2017','14/09/2018','06/08/2016']
重要信息
- 这些列表中的数据将随其大小而变化,但它们将保持相同的数据类型。
- 每个列表的第一个元素都是链接的,第二个和第三个元素也是如此......
所需的命令行界面:
Product | Price | Date of Purchase
--------|-------|------------------
apple | £0.11 | 02/04/2017
--------|-------|------------------
banana | £0.07 | 14/09/2018
--------|-------|------------------
orange | £0.05 | 06/08/2016
我想创建一个这样的表。如果每个列表中有更多元素,它显然应该继续,但我不知道如何创建它。
我可以做到
print(""" Product | Price | Date of Purchase # etc...
--------|-------|------------------
%s | %s | %s
""" % (products[0],prices[0],dates[0]))
但我认为这会对界面进行硬编码,这并不理想,因为列表的长度未确定
有什么帮助吗?
最佳答案
如果您想要一个不使用库的版本,这里有一个相当简单的函数,它使用了一些列表推导式
def print_table(headers, *columns):
# Ignore any columns of data that don't have a header
columns = columns[:len(headers)]
# Start with a space to set the header off from the left edge, then join the header strings with " | "
print(" " + " | ".join(headers))
# Draw the header separator with column dividers based on header length
print("|".join(['-' * (len(header) + 2) for header in headers]))
# Iterate over all lists passed in, and combine them together in a tuple by row
for row in zip(*columns):
# Center the contents within the space available in the column based on the header width
print("|".join([
col.center((len(headers[idx]) + 2), ' ')
for idx, col in enumerate(row)
]))
这不会处理长于列标题长度 + 2 的单元格值。但是通过截断单元格内容很容易实现(可以看到字符串截断的示例 here )。
关于python - 设计带有列表的可扩展命令行界面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53953808/