2014-12-02 56 views
0

我有一个CSV文件中的数据,它告诉我们一个篮球运动员是否肥胖。我可以使用python中的if语句创建一个对齐表吗?

我需要从这个数据做一个完全对齐的表;我有所有的信息来判断一个球员是否肥胖。但是,我有一个“if”语句,可以输出每个肥胖球员的值,并且我需要将这个打印输出成整齐的,对齐的行。

我:

obese_count = 0 
total_count = 0 


print (" " * 5, "First Name", " " * 2, "Last Name", " " * 2, "Height"," " * 2,"Weight"," " * 2, "BMI") # header 
print ("- " * 20) 
for player in players: 
    if has_data(player): 
     if is_obese(player): 
      print (" " * 5, player["firstname"]," " * 5, player["lastname"]," " * 9, player["h_feet"]," " * 9,player["h_inches"]," " * 5, player["weight"]) 
      obese_count += 1 
     total_count += 1 

它返回一个极其潦草表:

 First Name Last Name Height Weight BMI 
- - - - - - - - - - - - - - - - - - - - 
     Carlos  Boozer   6   9  280 
     Elton  Brand   6   8  275 
     Glen  Davis   6   9  289 
     Thomas  Hamilton   7   2  330 
     James  Lang   6   10  305 
     Jason  Maxiell   6   7  280 
     Oliver  Miller   6   9  280 
     Craig  Smith   6   7  272 
     Robert  Traylor   6   8  284 
     Jahidi  White   6   9  290 

我想知道是否有什么办法,我可以整理这件事,让我能有一个整洁和对齐的表或至少对齐的行没有不同的间隔。

+0

[Fancier Output Formatting](https://docs.python.org/2/tutorial/inputoutput.html) – 2014-12-02 22:07:03

+0

如[Format Specification Mini-Language](https://docs.python.org/)所示3/library/string.html#formatspec)文档中,您可以使用'width'来定义每个字段与其中一个“对齐”字符的结合宽度(''''''''=''|'“^” ')让它看起来不错。 – martineau 2014-12-02 22:12:00

回答

2

String formatting是你的朋友。

例如,

print '{:<10} {:<10} {:>2}\' {:>2}" {:>6}'.format(player["firstname"], player["lastname"], player["h_feet"], player["h_inches"], player["weight"]) 

这应返回是这样的:

Carlos  Boozer  6' 9" 280 
Elton  Brand  6' 8" 275 
Glen  Davis  6' 9" 289 

顺便说一句:它看起来像你的表有BMI头,但有没有相应的字段你的球员字典。

+0

谢谢,我只是在那里添加了;我甚至没有注意到。但是当我尝试你的建议时出现错误:'TypeError:传递给对象.__格式___的非空格式字符串。有什么办法可以解决这个问题吗? – ComputerHelp 2014-12-02 22:32:26

+0

我不完全确定是什么原因导致了这个错误,但是这与你传递给'.format()'的数据类型有关。我猜这是数字,所以我会在'str()'中包装'player(“h_feet”)'来获得:'str(player(“h_feet”))''。对h_inches,体重和BMI做同样的事情,看看是否有效。 – jgysland 2014-12-02 22:42:46

+0

FWIW,我在为示例编写代码时做了数字字符串。 ''''姓'':'卡洛斯','姓':'布泽尔','h_feet':'6','h_inches':'9','重量':'280'},...' – jgysland 2014-12-02 22:44:35

0

Python documentation解释得非常好。

>>> for x in range(1,11): 
...  print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x) 
... 
1 1 1 
2 4 8 
3 9 27 
4 16 64 
5 25 125 
6 36 216 
7 49 343 
8 64 512 
9 81 729 
10 100 1000 
相关问题