2015-11-01 112 views
1

如何打印列中的Python值?列中的Python打印列表

我整理他們,但我不知道如何將它們打印兩種方式 例如:

list=['apricot','banana','apple','car','coconut','baloon','bubble'] 

第一招:

apricot  bubble  ... 
apple  car   
baloon  coconut 

方式二:

apricot apple  baloon 
bubble  car  coconut 

我也想把所有的東西都調整到ljust/rjust。

我想是這樣的:

print " ".join(word.ljust(8) for word in list) 

,但只顯示像第一個例子。我不知道這是否是正確的方法。

+1

有沒有建立這樣做的方式,你將不得不自己編程。 – sth

+0

你試圖解決這個問題? –

+0

我試過類似這樣的內容:print「」.join(word.ljust(8)for word in list)但它只顯示在第一個例子中。我不知道這是做這件事的正確方法。 – Knight

回答

1
the_list = ['apricot','banana','apple','car','coconut','baloon','bubble'] 
num_columns = 3 

for count, item in enumerate(sorted(the_list), 1): 
    print item.ljust(10), 
    if count % num_columns == 0: 
     print 

輸出:

apple  apricot baloon  
banana  bubble  car  
coconut 

UPDATE: 這裏是全面的解決方案,可以滿足你已經給這兩個例子。我已經爲此創建了一個函數,並且我已經評論了代碼,以便清楚地理解它正在做什麼。

def print_sorted_list(data, rows=0, columns=0, ljust=10): 
    """ 
    Prints sorted item of the list data structure formated using 
    the rows and columns parameters 
    """ 

    if not data: 
     return 

    if rows: 
     # column-wise sorting 
     # we must know the number of rows to print on each column 
     # before we print the next column. But since we cannot 
     # move the cursor backwards (unless using ncurses library) 
     # we have to know what each row with look like upfront 
     # so we are basically printing the rows line by line instead 
     # of printing column by column 
     lines = {} 
     for count, item in enumerate(sorted(data)): 
      lines.setdefault(count % rows, []).append(item) 
     for key, value in sorted(lines.items()): 
      for item in value: 
       print item.ljust(ljust), 
      print 
    elif columns: 
     # row-wise sorting 
     # we just need to know how many columns should a row have 
     # before we print the next row on the next line. 
     for count, item in enumerate(sorted(data), 1): 
      print item.ljust(ljust), 
      if count % columns == 0: 
       print 
    else: 
     print sorted(data) # the default print behaviour 


if __name__ == '__main__': 
    the_list = ['apricot','banana','apple','car','coconut','baloon','bubble'] 
    print_sorted_list(the_list) 
    print_sorted_list(the_list, rows=3) 
    print_sorted_list(the_list, columns=3) 
+0

非常感謝:)你能告訴我,如果有方法打印它,就像我在第一個例子中顯示的那樣? – Knight

+1

@bartekshadow我已經更新了我的答案,以包含一個解決方案,也可以滿足您的第一個示例。 – dopstar