循环打印两个列表,以获得两列在每个列表的每个元素的第一个字母之间具有固定(自定义集)空间

时间:2012-08-23 12:32:09

标签: python list loops for-loop pretty-print

假设我有这两个列表:

column1 = ["soft","pregnant","tall"]
column2 = ["skin","woman", "man"]

如何使用自定义的固定空间(例如10,如示例)循环打印这两个列表,从第一个列表的每个元素的第一个字母开始直到第二个列表的每个元素的第一个字母列出?

设置间距为10的示例输出:

soft      skin
pregnant  woman 
tall      man

5 个答案:

答案 0 :(得分:8)

使用string formatting

轻松完成
column1 = ["soft","pregnant","tall"]
column2 = ["skin","woman", "man"]

for c1, c2 in zip(column1, column2):
    print "%-9s %s" % (c1, c2)

或者您可以使用str.ljust,如果您希望填充基于变量,则更整洁:

padding = 9
for c1, c2 in zip(column1, column2):
    print "%s %s" % (c1.ljust(padding), c2)

(注意:填充为9而不是10,因为这些字之间存在硬编码空间)

答案 1 :(得分:5)

怎么样:

>>> column1 = ["soft","pregnant","tall"]
>>> column2 = ["skin","woman", "man"]
>>> for line in zip(column1, column2):
...     print '{:10}{}'.format(*line)
... 
soft      skin
pregnant  woman
tall      man

答案 2 :(得分:3)

column1 = ["soft","pregnant","tall"]
column2 = ["skin","woman", "man"]

for row in zip(column1, column2):
    print "%-9s %s" % row # formatted to a width of 9 with one extra space after

答案 3 :(得分:1)

使用Python 3

column1 = ["soft","pregnant","tall"]
column2 = ["skin","woman", "man"]

for line in zip(column1, column2):
    print('{:10}{}'.format(*line))

答案 4 :(得分:0)

使用新样式字符串格式的一个班轮:

>>> column1 = ["soft", "pregnant", "tall"]
>>> column2 = ["skin", "woman", "man"]

>>> print "\n".join("{0}\t{1}".format(a, b) for a, b in zip(column1, column2))

soft        skin
pregnant    woman
tall        man