我可以用python中的if语句创建一个对齐的表吗?

2024-09-28 21:49:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个CSV文件中的数据,它告诉我一个篮球运动员是否肥胖。你知道吗

我需要根据这些数据制作一个完全对齐的表格;我有所有的信息来判断一个玩家是否肥胖。但是,我有一个“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

我想知道是否有什么方法可以整理一下,这样我就可以有一个整洁的、对齐的表,或者至少是对齐的行,它们之间的间隔不会有差异。你知道吗


Tags: csv数据nameifcount玩家totalfirst
2条回答

Pythondocumentation很好地解释了这一点。你知道吗

>>> 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

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的标题,但在播放器字典中没有相应的字段。你知道吗

相关问题 更多 >