索引错误:列表索引超出范围 - Python

3
我遇到了以下错误:
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

以下是输入/输出示例:

Please enter the amount of money to convert: 100
['Pound Sterling', 'Euro', 'US Dollar', 'Japanese Yen']
Please enter the current currency: Pound Sterling

4
我发现谦逊的“print”语句非常有效...例如,您可以使用它来查看“row”中的内容。 - kindall
正如@kindall所说,你能放几个打印语句并展示它们输出了什么吗?或者你可以展示一下exchangeRate.csv里面有什么内容... - A.J. Uppal
我不明白那有什么用处? - user3165683
1
你不认为知道 row 是否有第零个元素,或者它是否实际上是一个列表会很有用吗? - kindall
2个回答

3
您的CSV文件中可能有空行,导致它产生一个空列表。
有几种解决方案:
1. 检查是否有元素,只有在有元素的情况下才继续:
for row in exchReader:
    if len(row):  # can also just do   if row:
        currency = row[0]
        if currency == crntCurrency:

2. 通过短路运算符使 currency 变成一个空列表,这样就不会匹配 crntCurrency

for row in exchReader:
    currency = row and row[0]
    if currency == crntCurrency:

2

尝试打印行。Python 中变量名的约定是like_this而不是likeThis。你可能会发现break关键字很有用:

for row in exch_reader:
    currency = row[0]
    if currency == crnt_currency:
        crnt_rt = row[1]
        break

只有当行实际包含内容时才索引该行:

currency = row and row[0]

这里的row[0]只有在row求值为True时才会被执行,这意味着至少有一个元素。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接