Python列表格式

时间:2014-11-22 18:29:52

标签: python list tabs formatting alignment

我有一个带有此文件的.txt文件(加上更多名字):

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

等等

2 个答案:

答案 0 :(得分:0)

只需使用'\t'字符串加入嵌套列表:

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

首先需要map(str, ...)将您的计数转换为字符串。

然而,数字不一定会集中在一起;制表符移动光标&#39;到下一个标签位置,如果前面的文字不够长,可能比你预期的要早。

你可以简单地使用字符串格式来填充带有空格的第一列;您可以将其基于第一列的最大长度:

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

答案 1 :(得分:0)

Capabilities

我刚刚解决了你的问题非常简单的道路。 :)