2014-11-22 74 views
0

我有這個就可以了(還有個名字).txt文件:Python列表格式

Boston Americans 
New York Giants 
Chicago White Sox 
Chicago Cubs 
Chicago Cubs 
Pittsburgh Pirates 

我創建了一個清單,然後做了多少次,我得到相同的隊伍計數。

然後我得到這個:

[['New York Giants', 5], ['Anaheim Angels', 1], ['Detroit Tigers', 4], ['St. Louis Cardinals', 11], ['Minnesota Twins', 2], ['Florida Marlins', 2], ['Boston Red Sox', 7], ['Oakland Athletics', 4], ['Los Angeles Dodgers', 5], ['Philadelphia Athletics', 5] 

我如何可以反過來說,名單出來是這樣的:

New York Giants (\t tab) 5 
Anaheim Angels (tab) 1 
Detroit Tigers (tab) 4   <----- with all the numbers centered 
St. Louis Cardinals (tab) 11 
Minnesota Twins (tab) 2 

回答

0

簡單地用'\t'加入您的嵌套列表字符串:

newlist = ['\t'.join(map(str, sublist)) for sublist in outerlist] 

需要map(str, ...)將您的計數轉換爲字符串。

然而,數字並不一定以居中爲準;選項卡字符會將「光標」移動到下一個選項卡位置,如果前面的文本不夠長,這可能比您預期的要早。

您可以簡單地使用字符串格式來填充第一列的空格;你可以在第一列的最大長度爲基礎的:

max_team_width = max(len(item[0]) for item in outerlist) 
max_count_width = max(len(str(item[1])) for item in outerlist) 
for item in outerlist: 
    print('{item[0]:{team_width}} {item[1]:{count_width}d}'.format(
     team_width=max_team_width, count_width=max_count_width, item=item)) 

打印的項目,但你也可以只將結果添加到列表中仍然。

後者生產:

>>> team_counts = [ 
...  ['New York Giants', 5], 
...  ['Anaheim Angels', 1], 
...  ['Detroit Tigers', 4], 
...  ['St. Louis Cardinals', 11], 
...  ['Minnesota Twins', 2], 
... ] 
>>> max_team_width = max(len(item[0]) for item in team_counts) 
>>> max_count_width = max(len(str(item[1])) for item in team_counts) 
>>> for item in team_counts: 
...  print('{item[0]:{team_width}} {item[1]:{count_width}d}'.format(
...   team_width=max_team_width, count_width=max_count_width, item=item)) 
... 
New York Giants  5 
Anaheim Angels  1 
Detroit Tigers  4 
St. Louis Cardinals 11 
Minnesota Twins  2 

而製表單獨的輸出可以用來生產:

>>> for item in team_counts: 
...  print('\t'.join(map(str, item))) 
... 
New York Giants 5 
Anaheim Angels 1 
Detroit Tigers 4 
St. Louis Cardinals 11 
Minnesota Twins 2 
+0

如何將我轉換列表中爲str:newlist = [ '\ T'。在子列表中加入(子列表)子列表] – adrianhmartinez 2014-11-22 18:55:25

+0

@adrianhmartinez:你可以在外部子列表中使用子列表:print('\ t'.join(子列表))'打印出加入製表符的字符串。 – 2014-11-22 18:58:17

+0

當我做newlist = ['\ t'.join(map(str,sublist))爲count列表中的子列表]它打印「\ t」,它實際上並沒有選項卡。 – adrianhmartinez 2014-11-22 21:31:09