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()中以使其更好地工作。

关于python - 您如何删除python中这4行的重复性?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59117482/

10-10 23:51