假设我有这两个列表:
column1 = ["soft","pregnant","tall"]
column2 = ["skin","woman", "man"]
如何使用自定义的固定空间(例如10,如示例)循环打印这两个列表,从第一个列表的每个元素的第一个字母开始直到第二个列表的每个元素的第一个字母列出?
设置间距为10的示例输出:
soft skin
pregnant woman
tall man
答案 0 :(得分:8)
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