5

如果我有一个这样的 6 长度列表:

l = ["AA","BB","CC","DD"]

我可以打印它:

print "%-2s %-2s %-2s %-2s" % tuple(l)

输出将是:

AA BB CC DD

但是如果列表 l 可以是任意长度呢?有没有办法用未知数量的元素以相同的格式打印列表?

4

3 回答 3

11

生成单独的片段并加入它们:

print ' '.join(['%-2s' % (i,) for i in l])

或者您可以使用字符串乘法:

print ('%-2s ' * len(l))[:-1] % tuple(l)

最后[:-1]去除多余的空间;你也可以使用.rstrip()

演示:

>>> print ' '.join(['%-2s' % (i,) for i in l])
AA BB CC DD
>>> print ' '.join(['%-2s' % (i,) for i in (l + l)])
AA BB CC DD AA BB CC DD
>>> print ('%-2s ' * len(l))[:-1] % tuple(l)
AA BB CC DD
>>> print ('%-2s ' * len(l))[:-1] % tuple(l + l)
AA BB CC DD AA BB CC DD

时间统计:

>>> def joined_snippets(l):
...     ' '.join(['%-2s' % (i,) for i in l])
... 
>>> def joined_template(l):
...     ' '.join(['%-2s' for i in l])%tuple(l)
... 
>>> def multiplied_template(l):
...     ('%-2s ' * len(l))[:-1] % tuple(l)
... 
>>> from timeit import timeit
>>> l = ["AA","BB","CC","DD"]
>>> timeit('f(l)', 'from __main__ import l, joined_snippets as f')
1.3180170059204102
>>> timeit('f(l)', 'from __main__ import l, joined_template as f')
1.080280065536499
>>> timeit('f(l)', 'from __main__ import l, multiplied_template as f')
0.7333378791809082
>>> l *= 10
>>> timeit('f(l)', 'from __main__ import l, joined_snippets as f')
10.041708946228027
>>> timeit('f(l)', 'from __main__ import l, joined_template as f')
5.52706503868103
>>> timeit('f(l)', 'from __main__ import l, multiplied_template as f')
2.8013129234313965

倍增的模板选项将其他选项留在了尘埃中。

于 2013-06-07T12:21:51.183 回答
1

另一种方法

' '.join(['%-2s' for i in l])%tuple(l)

我发现这比使用生成器表达式快两倍以上

' '.join('%-2s' for i in l)%tuple(l)

这还是更快

'%-2s '*len(l)%tuple(l) # leaves an extra trailing space though
于 2013-06-07T12:26:18.277 回答
0
tests = [
    ["AA"],
    ["AA", "BB"],
    ["AA", "BBB", "CCC"]
]

for test in tests:
    format_str = "%-2s " * len(test)
    print format_str

--output:--
%-2s 
%-2s %-2s 
%-2s %-2s %-2s 
于 2013-06-07T12:26:07.337 回答