all_currencies = currency_api('latest', 'currencies') # {'eur': 'Euro', 'usd': 'United States dollar', ...}
all_currencies.pop('brl')
qtd_moedas = len(all_currencies)
texto = f'{qtd_moedas} Moedas encontradas\n\n'
moedas_importantes = ['usd', 'eur', 'gbp', 'chf', 'jpy', 'rub', 'aud', 'cad', 'ars']
while len(moedas_importantes) != 0:
for codigo, moeda in all_currencies.items():
if codigo == moedas_importantes[0]:
cotacao, data = currency_api('latest', f'currencies/{codigo}/brl')['brl'], currency_api('latest', f'currencies/{codigo}/brl')['date']
texto = f'{moeda} ({codigo.upper()}) = R$ {cotacao} [{data}]\n'
moedas_importantes.remove(codigo)
if len(moedas_importantes) == 0: break # WITHOUT THIS LINE, GIVES ERROR
為什么我會收到此錯誤?串列實際上用完了元素,但代碼僅適用于 if
uj5u.com熱心網友回復:
你有一個嵌套回圈。進入while回圈,然后在for回圈中立即開始執行。對于 中的所有元素,執行仍在 for 回圈中all_currencies.items()
。每次codigo
在 的開頭找到時moedas_importantes
,都會洗掉該元素。最終您從 中洗掉所有元素moedas_importantes
,但您仍處于 for 回圈中并檢查if codigo == moedas_importantes[0]
. 此時moedas_importantes
為空,因此您會收到索引錯誤。
我認為下面的代碼將在沒有嵌套回圈的情況下作業。請注意,這假定 in 中的所有元素moedas_importantes
也是 中的鍵all_currencies
。
all_currencies = currency_api('latest', 'currencies') # {'eur': 'Euro', 'usd': 'United States dollar', ...}
all_currencies.pop('brl')
qtd_moedas = len(all_currencies)
texto = f'{qtd_moedas} Moedas encontradas\n\n'
moedas_importantes = ['usd', 'eur', 'gbp', 'chf', 'jpy', 'rub', 'aud', 'cad', 'ars']
while len(moedas_importantes) != 0:
codigo = moedas_importantes[0]
moeda = all_currencies[codigo]
cotacao, data = currency_api('latest', f'currencies/{codigo}/brl')['brl'], currency_api('latest', f'currencies/{codigo}/brl')['date']
texto = f'{moeda} ({codigo.upper()}) = R$ {cotacao} [{data}]\n'
moedas_importantes.remove(codigo)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/470917.html