【问题标题】:Formatting print function with list comprehensions使用列表推导格式化打印功能
【发布时间】:2021-09-18 11:37:27
【问题描述】:

我正在尝试编写一个代码来格式化列表理解函数[print('{:<15} ${:<4f}'.format(Timeframes[counter],x)) for counter,x in enumerate(Compounding)],以便打印预期的输出。我正在尝试在同一行上打印 CompoundingNon_Compounding 的值,但我尝试执行的 Print Function 不起作用。我怎样才能像预期输出一样运行它?

代码:

import numpy as np

Timeframes = ['Last Month:', 'Three Months:', 'Six Months:', 'Last Year:', 'Last Two Years:', 'Entirety:']
Compounding = np.array([97.44704833566995, 77.20626280482892, 232.04635122144302, 424.5742707027069, 4076.195731389482, 28513.877490504994])
NonCompounding = np.array([98.7019108522086, 79.00055035682558, 198.89764228943147, 268.25878090471525, 514.6930939260048, 938.811329948405])

print("\t\tCompounding ")
[print('{:<15} ${:<4f}'.format(Timeframes[counter],x)) for counter,x in enumerate(Compounding)]
print("\n\t\tNon Compounding: ")
[print('{:<15} ${:<4f}'.format(Timeframes[counter],x)) for counter,x in enumerate(NonCompounding)]

打印功能:

[print('{:<15} ${:<4f}\t\t${:<4f}'.format(Timeframes[counter],x,y)) for counter,x,y in enumerate(Compounding,NonCompounding)]

输出

                Compounding 
Last Month:     $97.447048
Three Months:   $77.206263
Six Months:     $232.046351
Last Year:      $424.574271
Last Two Years: $4076.195731
Entirety:       $28513.877491

                Non Compounding: 
Last Month:     $98.701911
Three Months:   $79.000550
Six Months:     $198.897642
Last Year:      $268.258781
Last Two Years: $514.693094
Entirety:       $938.811330

预期输出:

                Compounding        Non Compounding
Last Month:     $97.447048         $98.701911
Three Months:   $77.206263         $79.000550
Six Months:     $232.046351        $198.897642
Last Year:      $424.574271        $268.258781
Last Two Years: $4076.195731       $514.693094
Entirety:       $28513.877491      $938.811330

【问题讨论】:

  • 不要使用列表推导进行循环,使用普通的for 循环。

标签: python arrays numpy for-loop printing


【解决方案1】:

使用zip() 并行循环列表。

for timeframe, compound, noncompound in zip(TimeFrames, Compounding, NonCompounding):
    print(f'{timeframe:<15} ${compound{:<4f} ${noncompund:<4f}')

不需要列表理解。 print() 不返回任何内容,因此您只是在创建一个包含 None 的列表。而且您不会在任何地方分配结果列表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-15
    • 2013-10-24
    • 1970-01-01
    • 2020-07-25
    • 1970-01-01
    • 2016-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多