2015-11-01 114 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