首页 > 解决方案 > 列表中的表格数据

问题描述

我对 python 的经验很少,我目前正在尝试从以下数据构建一个表格,这些数据是从一个 while 循环构建的。

Fahrenheit = 0
CTempList = [0]
FTempList = []
NameList = ["Temperature in Celsius "," Temperature in Fahrenheit"]
while (Celsius <= 100):
    Fahrenheit = (Celsius * 9/5) + 32
    FTempList.append(Fahrenheit)
    Celsius = Celsius + 5 

我想构建一个看起来像这样的表格,目前我无法使用诸如 prettytable 或 tabulate 之类的模块。

Temperatures     Temperature
in Celcius       in Fahrenheit
------------------------------
  0        |           32.0
  5        |           41.0
 10        |           50.0
 15        |           59.0
 20        |           68.0
 25        |           77.0
 30        |           86.0
 35        |           95.0
 40        |          104.0
 45        |          113.0
 50        |          122.0
 55        |          131.0
 60        |          140.0
 65        |          149.0
 70        |          158.0
 75        |          167.0
 80        |          176.0
 85        |          185.0
 90        |          194.0
 95        |          203.0
100        |          212.0

标签: pythonlist

解决方案


您可以使用宽度以使其适合您的需要:

Fahrenheit = 0
CTempList = [0]
FTempList = []
NameList = ["Temperature in Celsius "," Temperature in Fahrenheit"]
Celsius = CTempList[0]
while (Celsius <= 100):
    Fahrenheit = (Celsius * 9/5) + 32
    FTempList.append(Fahrenheit)
    Celsius = Celsius + 5 
    CTempList.append(Celsius)
width = 15
header1 = 'Temperature'.ljust(width,' ')
header2 = 'in Celsius'.ljust(width,' ') + 'in Fahrenheit'.ljust(width,' ')
Header = header1+header1 + '\n' +header2
print(Header)
print('-'*(width+width))
for C, F in zip(CTempList, FTempList):
  line = str(C).rjust(3,' ') + '|'.rjust(10,' ') + str(F).center(width, ' ')
  print(line)

输出:

Temperature    Temperature
in Celsius     in Fahrenheit
------------------------------
  0         |      32.0
  5         |      41.0
 10         |      50.0
 15         |      59.0
 20         |      68.0
 25         |      77.0
 30         |      86.0
 35         |      95.0
 40         |     104.0
 45         |     113.0
 50         |     122.0
 55         |     131.0
 60         |     140.0
 65         |     149.0
 70         |     158.0
 75         |     167.0
 80         |     176.0
 85         |     185.0
 90         |     194.0
 95         |     203.0
100         |     212.0

推荐阅读