IndexError:列表索引超出范围-python [英] IndexError: list index out of range - python
本文介绍了IndexError:列表索引超出范围-python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我遇到以下错误:
currency = row[0]
IndexError: list index out of range
这是代码:
crntAmnt = int(input("Please enter the amount of money to convert: "))
print(currencies)
exRtFile = open ('exchangeRate.csv','r')
exchReader = csv.reader(exRtFile)
crntCurrency = input("Please enter the current currency: ")
validateloop=0
while validateloop == 0:
for row in exchReader:
currency = row[0]
if currency == crntCurrency:
crntRt = row[1]
validateloop=+1
在这里CSV文件:
日元169.948
美元,1.67
英镑,1
欧元,5.5
这是一个输入/输出示例:
Here's an input/Output example:
Please enter the amount of money to convert: 100
['Pound Sterling', 'Euro', 'US Dollar', 'Japanese Yen']
Please enter the current currency: Pound Sterling
推荐答案
您的csv文件中可能存在空白行,从而导致其生成一个空列表
You probably have a blank row in your csv file, causing it to produce an empty list
有几种解决方案
1.检查是否有元素,只有在存在时才继续:
1. Check if there are elements, only proceed if there are:
for row in exchReader:
if len(row): # can also just do if row:
currency = row[0]
if currency == crntCurrency:
2.短路and
运算符以使currency
为空列表,该列表与crntCurrency
不匹配:
2. Short-circuit an and
operator to make currency
an empty list, which won't match crntCurrency
:
for row in exchReader:
currency = row and row[0]
if currency == crntCurrency:
这篇关于IndexError:列表索引超出范围-python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文