对于循环不尊重继续命令

时间:2016-09-02 16:45:11

标签: python for-loop continue

我遇到的问题是continue命令跳过不一致。它会跳过数字输出ebitda,但会在其旁边放置不正确的ticker。为什么是这样?如果我只是在phm输入一个输入它应该跳过,它会正确打印一个空列表[]但是当一个无效的自动收报机放在一个有效的一个旁边时,混乱就会开始发生。

import requests

ticker = ['aapl', 'phm', 'mmm']
ebitda = []


for i in ticker:

    r_EV=requests.get('https://query2.finance.yahoo.com/v10/finance/quoteSummary/'+i+'?formatted=true&crumb=8ldhetOu7RJ&lang=en-US&region=US&modules=defaultKeyStatistics%2CfinancialData%2CcalendarEvents&corsDomain=finance.yahoo.com')
    r_ebit = requests.get('https://query1.finance.yahoo.com/v10/finance/quoteSummary/' + i + '?formatted=true&crumb=B2JsfXH.lpf&lang=en-US&region=US&modules=incomeStatementHistory%2CcashflowStatementHistory%2CbalanceSheetHistory%2CincomeStatementHistoryQuarterly%2CcashflowStatementHistoryQuarterly%2CbalanceSheetHistoryQuarterly%2Cearnings&corsDomain=finance.yahoo.com%27')

    data = r_EV.json()
    data1 = r_ebit.json()

    if data1['quoteSummary']['result'][0]['balanceSheetHistoryQuarterly']['balanceSheetStatements'][0].get('totalCurrentAssets') == None:
        continue #skips certain ticker if no Total Current Assets available (like for PHM)

    ebitda_data = data['quoteSummary']['result'][0]['financialData']
    ebitda_dict = ebitda_data['ebitda']
    ebitda.append(ebitda_dict['raw']) #navigates to dictionairy where ebitda is stored

ebitda_formatted = dict(zip(ticker, ebitda))

print(ebitda_formatted)
# should print {'aapl': 73961996288, 'mmm': 8618000384}
# NOT: {'aapl': 73961996288, 'phm': 8618000384}

1 个答案:

答案 0 :(得分:2)

continue效果很好。您生成此列表:

[73961996288, 8618000384]

但是,然后您使用ticker将该列表压缩,其中仍包含3个元素,包括'phm'。当其中一个iterables为空时zip()停止,因此您生成以下元组:

>>> ebitda
[73961996288, 8618000384]
>>> ticker
['aapl', 'phm', 'mmm']
>>> zip(ticker, ebitda)
[('aapl', 73961996288), ('phm', 8618000384)]

如果您有选择地ebitda值添加到列表中,您还必须记录您处理的ticker个值:

used_ticker.append(i)

并使用该新列表。

或者您可以使用空ebitda_formatted词典启动并在循环中添加

ebitda_formatted[i] = ebitda_dict['raw']