Python 中的数据表

发布于 2024-12-01 00:55:45 字数 330 浏览 0 评论 0原文

我在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

梦巷 2024-12-08 00:55:45
l = [['Something', 'Something else', 'Another thing'],
     ['Other things', 'More data', 'Element'],
     ['Stuff', 'data', 'etc']]
sub1 = [
    [s.ljust(max(len(i) for i in column)) for s in column]
    for column in zip(*l)]
for p in [" ".join(row) for row in zip(*sub1)]: print p

在这里,首先使用 zip(*l) 转换列表:每个子列表都作为自己的参数传递给 zip()。结果是一个列表,其中组合了每个旧列表的第 n 个条目,因此您得到 [['Something', 'Other things', 'Stuff'], ['Something else', 'More data', '数据'],...]

那么要匹配长度的条目就在同一中。在每一列中,字符串都被 ljust() 调整为组中的最大长度。

之后,长度调整后的新列表将再次进行转换 - 以与上面相同的方式 - 并且组件之间用 " " 连接。

然后逐项打印生成的一维列表。

l = [['Something', 'Something else', 'Another thing'],
     ['Other things', 'More data', 'Element'],
     ['Stuff', 'data', 'etc']]
sub1 = [
    [s.ljust(max(len(i) for i in column)) for s in column]
    for column in zip(*l)]
for p in [" ".join(row) for row in zip(*sub1)]: print p

Here, first the list gets transformed with zip(*l): each of the sub lists gets passed as an own argument to zip(). 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 these columns the strings are ljust()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.

赠佳期 2024-12-08 00:55:45

您可以使用字符串 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.

木落 2024-12-08 00:55:45
from itertools import chain

ll = [['Something', 'Something else', 'Another thing'],
 ['Other things', 'More data', 'Element'],
 ['Stuff', 'data', 'etc']]

# get the length of the longest item. 
# For simplicity, I use the same width for all columns
a = max(len(s) for s in chain.from_iterable(ll)) + 1 

# make a format string with the max
f = ('{:<' + str(a) + '}').format

# print the list
print '\n'.join(''.join(f(s) for s in sl) for sl in ll)
from itertools import chain

ll = [['Something', 'Something else', 'Another thing'],
 ['Other things', 'More data', 'Element'],
 ['Stuff', 'data', 'etc']]

# get the length of the longest item. 
# For simplicity, I use the same width for all columns
a = max(len(s) for s in chain.from_iterable(ll)) + 1 

# make a format string with the max
f = ('{:<' + str(a) + '}').format

# print the list
print '\n'.join(''.join(f(s) for s in sl) for sl in ll)
梦毁影碎の 2024-12-08 00:55:45

我不知道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".

似最初 2024-12-08 00:55:45
li = [['Something', 'Something else', 'Another thing'],
      ['Other things', 'More data', 'Element'],
      ['Stuff', 'data', 'etc']]

print li,'\n'

print "tuple( max(map(len,x)) for x in zip(*li)) == ",\
      tuple( max(map(len,x)) for x in zip(*li))


print
patform = '%%-%ss %%-%ss %%-%ss' % tuple( max(map(len,x)) for x in zip(*li))
print '\n'.join(patform % tuple(x) for x in li)

# OR

print
patform = '{:<%s} {:<%s} {:<%s}' % tuple( max(map(len,x)) for x in zip(*li))
print '\n'.join(patform.format(*x) for x in li)

# OR

print
patform = '{{:<{}}} {{:<{}}} {{:<{}}}'.format( *tuple( max(map(len,x)) for x in zip(*li)) )
print '\n'.join(patform.format(*x) for x in li)

结果

[['Something', 'Something else', 'Another thing'], ['Other things', 'More data', 'Element'], ['Stuff', 'data', 'etc']] 

tuple( max(map(len,x)) for x in zip(*li)) ==  (12, 14, 13)

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          

Something    Something else Another thing
Other things More data      Element      
Stuff        data           etc  
li = [['Something', 'Something else', 'Another thing'],
      ['Other things', 'More data', 'Element'],
      ['Stuff', 'data', 'etc']]

print li,'\n'

print "tuple( max(map(len,x)) for x in zip(*li)) == ",\
      tuple( max(map(len,x)) for x in zip(*li))


print
patform = '%%-%ss %%-%ss %%-%ss' % tuple( max(map(len,x)) for x in zip(*li))
print '\n'.join(patform % tuple(x) for x in li)

# OR

print
patform = '{:<%s} {:<%s} {:<%s}' % tuple( max(map(len,x)) for x in zip(*li))
print '\n'.join(patform.format(*x) for x in li)

# OR

print
patform = '{{:<{}}} {{:<{}}} {{:<{}}}'.format( *tuple( max(map(len,x)) for x in zip(*li)) )
print '\n'.join(patform.format(*x) for x in li)

result

[['Something', 'Something else', 'Another thing'], ['Other things', 'More data', 'Element'], ['Stuff', 'data', 'etc']] 

tuple( max(map(len,x)) for x in zip(*li)) ==  (12, 14, 13)

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          

Something    Something else Another thing
Other things More data      Element      
Stuff        data           etc  
塔塔猫 2024-12-08 00:55:45
print '\n'.join([line+' ' for line in l])
print '\n'.join([line+' ' for line in l])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文