简体   繁体   English

你将如何删除python中这4行的重复性?

[英]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']

I feel like this bit of code is very repetitive, and was wondering how I could simplify it?我觉得这段代码很重复,想知道​​如何简化它?

Thank you in advance先感谢您

Something like this might help:像这样的事情可能会有所帮助:

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)

if in you version of python map() returns <map object> or something, you might want to wrap that in list() to make it work better.如果在您的 python map()版本中返回<map object>或其他东西,您可能希望将其包装在list()以使其更好地工作。

Just use a single dictionary instead of multiple variables:只需使用单个字典而不是多个变量:

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

Or a dict comprehension:或字典理解:

income_by_year = {year: json_r['financials'][year]['Net Income'] 
                  for year in range(0, 4)}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM