For循环不执行Continue命令

2024-09-28 01:28:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我遇到的问题是continue命令的跳过不一致。它跳过数值输出ebitda,但将不正确的ticker放在它旁边。为什么会这样?如果我让ticker只是phm一个它应该跳过的输入,它会正确地打印一个空列表[],但是当一个无效的ticker放在一个有效的ticker旁边时,混乱就开始发生了。你知道吗

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}

Tags: comdatagetrequestsdictyahoousticker
1条回答
网友
1楼 · 发布于 2024-09-28 01:28:14

continue工作正常。您将生成以下列表:

[73961996288, 8618000384]

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

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

相关问题 更多 >

    热门问题