如果我有这样的6长度列表:
l = ["AA","BB","CC","DD"]
我可以用以下方式打印:
print "%-2s %-2s %-2s %-2s" % tuple(l)
输出将是:
AA BB CC DD
但是如果列表l可以是任何长度怎么办?有没有办法以相同的格式打印具有未知数量元素的列表?
答案 0 :(得分:9)
生成单独的片段并加入它们:
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
相乘的模板选项将其他选项留在灰尘中。
答案 1 :(得分: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
答案 2 :(得分: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