[英]how would you delete the repetitiveness of these 4 lines in python?
Most_Recent_Net_Income = float(json_r['financials'][0]['Net Income'])
Net_income_1_year = float(json_r['financials'][1]['Net Income'])
Net_income_2_year = float(json_r['financials'][2]['Net Income'])
Net_income_3_year = json_r['financials'][3]['Net Income']
Net_income_4_year = json_r['financials'][4]['Net Income']
我觉得这段代码很重复,想知道如何简化它?
先感谢您
像这样的事情可能会有所帮助:
incomes = [i['Net Income'] for i in json_r['financials'][:5]]
Most_Recent_Net_Income, Net_income_1_year, Net_income_2_year,
Net_income_3_year, Net_income_4_year = map( float, incomes)
如果在您的 python map()
版本中返回<map object>
或其他东西,您可能希望将其包装在list()
以使其更好地工作。
只需使用单个字典而不是多个变量:
income_by_year = {}
for year in range(0, 5):
income_by_year[year] = json_r['financials'][year]['Net Income']
print('Income in year 4:', income_by_year[4])
或字典理解:
income_by_year = {year: json_r['financials'][year]['Net Income']
for year in range(0, 4)}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.