我正在尝试创建一个表,该表循环遍历各种风速值,以便计算如下所示的表:Ideal Run。但是,一旦我运行以下代码:
import math
y=' '
print("Big Blue Wind Chill")
print(y)
airTemp=float(input("Enter air temperature (F): "))
startWS=eval(input("Enter starting wind speed (mph): "))
print(y)
print("Temperature = " + str(airTemp) + " degrees F")
print(y)
entries = x = [[] for i in range(91-startWS)]
def Main():
i=startWS
for i in range(startWS,91):
entries[i-startWS].append(i)
i=i+1
Main()
def oldForumula():
i=startWS
for i in range(startWS,91):
old=round(0.081*(3.71*math.sqrt(i)+5.81-0.25*i)*(airTemp-91.4)+91.4)
entries[i-startWS].append(old)
i=i+1
oldForumula()
def newForumula():
i=startWS
for i in range(startWS,91):
new=round(35.74+0.6215*airTemp-35.75*(i**0.16)+0.4275*airTemp*(i**0.16))
#print(new)
entries[i-startWS].append(new)
i=i+1
newForumula()
def difference():
i=startWS
for i in range(startWS,91):
diff=round((0.081*(3.71*math.sqrt(i)+5.81-0.25*i)*(airTemp-91.4)+91.4)-(35.74+0.6215*airTemp-35.75*(i**0.16)+0.4275*airTemp*(i**0.16)),1)
#print(diff)
entries[i-startWS].append(diff)
i=i+1
difference()
print('Wind Speed', 'Old Formula', 'New Formula', 'Difference', sep='\t')
print(y)
for i in range(len(entries)):
for j in range(4):
print(entries[i][j], end='\t\t')
print()
我最终创建了表,但是列名和实际数值的对齐方式完全不对。运行以下代码后,外观如下所示:Actual run。如果您能帮助我修正对齐方式,我将不胜感激。
答案 0 :(得分:1)
您可以使用Format Specification Mini-Language使用字符串格式。
例如:
for i in range(len(entries)):
print("{0:>6.2f}\t{1:>6.2f}\t{2:>6.2f}\t{3:>6.2f}".format(*entries[i]))
您得到类似的东西:
Wind Speed Old Formula New Formula Difference
5.00 9.00 4.00 5.10
6.00 5.00 2.00 2.80
7.00 2.00 1.00 0.80
8.00 -1.00 0.00 -1.10
9.00 -3.00 0.00 -2.80
10.00 -5.00 -1.00 -4.30
11.00 -7.00 -2.00 -5.70
或者,使用更多的pythonic循环:
for entry in entries:
print("{0:>6.2f}\t{1:>6.2f}\t{2:>6.2f}\t{3:>6.2f}".format(*entry))
答案 1 :(得分:0)
您可以使用str.format()填充空格。
def draw_padded_string(s, width, align="left"):
if align == "left":
return "{s: <{width}}".format(s=s, width=width)
elif align == "center":
return s.center(width, ' ')
elif align == "right":
return "{s: >{width}}".format(s=s, width=width)
在这种情况下,s是字符串,而width是列的整个宽度。
您可以在代码中的某个位置定义此位置,可能是在您的导入下定义它,以使其脱离您的方式,但前提是在开始调用print语句之前已对其进行定义。这也会改变您的打印块:
width = 13
headers = ["Wind Speed", "Old Formula", "New Formula", "Difference"]
print_headers = []
for header in headers:
print_headers.append(draw_padded_string(header, width))
print("".join(print_headers))
print()
for row in entries:
print_row = []
for data in row:
print_row.append(draw_padded_string(data, width))
print("".join(print_row))
我做了什么:
"".join(list)
将列表打印为单行i
和j
使用自己的整数跟踪更改,改为让python为您遍历行和列您可能想做的不同的事情:
for item in list
column_length = max([len(word) for word in list_of_words])