9

假设我有这两个列表:

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

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

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

soft      skin
pregnant  woman 
tall      man
4

5 回答 5

9

轻松完成字符串格式化

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因为单词之间的硬编码空格)

于 2012-08-23T12:41:48.640 回答
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
于 2012-08-23T12:39:21.573 回答
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
于 2012-08-23T12:36:21.423 回答
1

使用 Python 3

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

for line in zip(column1, column2):
    print('{:10}{}'.format(*line))
于 2015-09-29T09:54:15.913 回答
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
于 2014-07-29T13:55:04.550 回答