Python 中的数据表
我在Python中有一个像这样的2D列表:
[['Something', 'Something else', 'Another thing'],
['Other things', 'More data', 'Element'],
['Stuff', 'data', 'etc']]
我希望它像这样打印出来:
Something Something else Another thing Other things More data Element Stuff data etc
I've got a 2D list in Python like this:
[['Something', 'Something else', 'Another thing'],
['Other things', 'More data', 'Element'],
['Stuff', 'data', 'etc']]
I want it to be printed out like this:
Something Something else Another thing Other things More data Element Stuff data etc
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在这里,首先使用
zip(*l)
转换列表:每个子列表都作为自己的参数传递给zip()
。结果是一个列表,其中组合了每个旧列表的第 n 个条目,因此您得到[['Something', 'Other things', 'Stuff'], ['Something else', 'More data', '数据'],...]
。那么要匹配长度的条目就在同一
列
中。在每一列中,字符串都被ljust()
调整为组中的最大长度。之后,长度调整后的新列表将再次进行转换 - 以与上面相同的方式 - 并且组件之间用
" "
连接。然后逐项打印生成的一维列表。
Here, first the list gets transformed with
zip(*l)
: each of the sub lists gets passed as an own argument tozip()
. The result is a list which combines the n-th entries of each old list, so you get[['Something', 'Other things', 'Stuff'], ['Something else', 'More data', 'data'], ...]
.Then the entries whose lengths are to be matched are in the same
column
. In each of thesecolumn
s the strings areljust()
ed to the greatest length in the group.After that, the new list with the adjusted lengths is transformed again - in the same way as above - and the components joined with a
" "
in-between.The resulting 1D list is then printed entry by entry.
您可以使用字符串
format
方法,甚至是较旧的字符串插值运算符,将字符串放入填充的固定长度字段中。请参阅格式字符串文档。使用它的循环不一定很难看。
You can use the string
format
method, or even the older string interpolation operator, to place strings into padded, fixed length fields. See format strings documentation.A loop using this need not be ugly.
我不知道Python库中是否存在这样的函数(我怀疑你会找到一个),但双重嵌套循环似乎是最简单的解决方案。只需将内部循环末尾的字符串与空格连接起来(但我猜从你提出问题的方式来看,你希望它们对齐,所以使用制表符转义字符“\t”)。退出内循环后打印它们,这样就可以了。
编辑:我发现我对制表符间距的看法是正确的...制表符转义字符相当于按制表符键,如果您需要更多空间,请连续使用多个“\t\t”。
I do not know if such a function exists in the python library (and I doubt you would find one), but a doubly nested loop seems to be the easiest solution. Simply concatenate the strings at the end of the inner loop with an empty space (but I guess from the way you asked the question, you want them aligned, so use the tab escape character "\t"). Print them after you exit the inner loop, and that should do it.
EDIT: I see I was right about the tab spacing ... the tab escape character is equivalent to pressing the tab key, if you need more space, use multiple ones in a row "\t\t".
结果
result