使用Python打印出像表一样的2D列表 [英] Printing out a 2D list like a table with Python
问题描述
我正在尝试打印出像桌子一样的2D列表,并且在这里找到了一段代码:漂亮的2D Python列表
但是我不知道它是如何工作的,有人可以向我解释吗?
s = [[行中e的str(e)]矩阵中的行]lens = [max(map(len, col)) for col in zip(*s)]fmt ='\ t'.join('{{:{}}}'.. format(x)for x in lens)table = [fmt.format(* row)for s in row]打印 '\n'.join(table)
正如其他人所评论的,这里有很多概念(太多的问题无法在一个答案中处理).但是,为了进行进一步的研究(使用(小的)示例2D列表依次尝试每个语句),请按以下步骤进行分解:
将数据转换为字符串列表(使用 list理解):
s = [[行中e的str(e)]矩阵中的行]
获取每列中最大字符数的列表,以便我们了解如何格式化列:
lens = [max(map(len, col)) for col in zip(*s)]
(这一点比较复杂: zip()
在这里使我们能够遍历 s
的列,并将它们分别传递给 len()
方法来查找其长度(这是通过 map()
实现的;然后使用内置的 max()
找到每一列的最大长度.)
将相应的Python格式字符串设置为制表符分隔的条目:
fmt ='\ t'.join('{{:{}}}'.format(x)for lens in x)
fmt
现在是每一行的格式说明符,例如'{:4} \ t {:6} \ t {:6}'
,用于宽度为4,6,6的三列(NB仅适用于Python 2.7+,因为字段尚未被使用编号)
将表设置为字符串格式的行列表(使用其他列表理解):
table = [s中的行的fmt.format(* row)]
用一个字符串将整个行连接在一起,行之间用换行符分隔:
打印'\ n'.join(表)
join()
提取一个字符串列表,并生成一个字符串,这些字符串均通过选定的定界符(此处为 \ n
,换行符)连接在一起./p>
I'm trying to print out a 2D list like a table, and I found a piece of code here: Pretty print 2D Python list
But I couldn't understand how it really works, can anyone please explain to me?
s = [[str(e) for e in row] for row in matrix]
lens = [max(map(len, col)) for col in zip(*s)]
fmt = '\t'.join('{{:{}}}'.format(x) for x in lens)
table = [fmt.format(*row) for row in s]
print '\n'.join(table)
As others have commented, there are a lot of concepts going on here (too many to be manageable in a single answer). But for your further study (try out each statement in turn with a (small) example 2D list), here's how it breaks down:
Turn the data into a list of lists of strings (uses list comprehension):
s = [[str(e) for e in row] for row in matrix]
Get a list of the maximum number of characters in each column so we know how to format the columns:
lens = [max(map(len, col)) for col in zip(*s)]
(This one is more complex: zip()
here enables us to iterate over the columns of s
, passing each to the len()
method to find its length (this is achieved with map()
); then find the maximum length of each column with the max()
builtin.)
Set up the corresponding Python format strings as tab-separated entries:
fmt = '\t'.join('{{:{}}}'.format(x) for x in lens)
fmt
is now the format specifier for every row, e.g. '{:4}\t{:6}\t{:6}'
for three columns with widths 4,6,6 (NB only works on Python 2.7+ because the fields haven't been numbered)
Set up the table as a list of rows in their string format (use another list comprehension):
table = [fmt.format(*row) for row in s]
Join the whole lot together in a single string, with rows separated by newlines:
print '\n'.join(table)
join()
takes a list of strings and produces one string with them all joined together by the chosen delimiter (here, \n
, the newline character).
这篇关于使用Python打印出像表一样的2D列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!