2012-08-23 45 views
8

假設我有這兩個列表中的每個元素的第一個字母之間的(自定義設置)空間:循環打印通過兩個列表以獲得兩列固定每個列表

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

如何循環打印通過這些兩個列表使用自定義的固定空間(例如,如10所示),從第一個列表的每個元素的第一個字母開始,直到第二個列表中的每個元素的第一個字母?的10的一組間隔的

輸出示例:

soft  skin 
pregnant woman 
tall  man 
+2

zip http://docs.python.org/library/functions.html#zip – bpgergo

回答

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因爲單詞之間的硬編碼空間)

+0

正如所寫的,這兩種解決方案在「懷孕」的「t」和「w」之間有三個空格,而不是兩個, 「女人」。我想,你可以刪除打印字符串中的空格。 – DSM

+0

假設第二列的元素將包含比我的終端屏幕寬度更長的字符串。默認行爲是這些字符串將溢出到我的第一列。如何讓每個這樣的長字符串從第二列的起點繼續? – Bentley4

+0

@DSM真,將填充量減1將完全匹配預期輸出。刪除'%s'之間的空格可能會導致單詞被一起淹沒。編輯回答 – dbr

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 
4

如何:

>>> column1 = ["soft","pregnant","tall"] 
>>> column2 = ["skin","woman", "man"] 
>>> for line in zip(column1, column2): 
...  print '{:10}{}'.format(*line) 
... 
soft  skin 
pregnant woman 
tall  man 
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 
0

使用Python 3

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

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