【问题标题】:Python 2.7: IndexError: list index out of rangePython 2.7:IndexError:列表索引超出范围
【发布时间】:2017-03-11 13:10:10
【问题描述】:

我正在尝试打开一个 csv 文件并将值从字符串转换为整数,以便对列表进行排序。我收到的结果是:

“[[], ['190'], ['200'], ['250'], ['350'], ['90']]”。

这是我的原始代码。

import csv

def bubbleSort(scores):
    for length in range(len(scores)-1,0,-1):
        for i in range(length):
            if scores[i]>scores[i+1]:
                temp = scores[i]
                scores[i] = scores[i+1]
                scores[i+1] = temp


with open ("rec_Scores.csv", "rb") as csvfile:
    r = csv.reader(csvfile)
    scores = list(r)


bubbleSort(scores)
print(scores)

我尝试在该行中添加:

scores_int = [int(score[0]) for score in scores]

但是现在我收到错误“IndexError: list index out of range”

这是我正在使用的代码的当前版本:

import csv

def bubbleSort(scores):
    for length in range(len(scores)-1,0,-1):
        for i in range(length):
            if scores[i]>scores[i+1]:
                temp = scores[i]
                scores[i] = scores[i+1]
                scores[i+1] = temp


with open ("rec_Scores.csv", "rb") as csvfile:
    r = csv.reader(csvfile)
    scores = list(r)
    scores_int = [int(score[0]) for score in scores]


bubbleSort(scores_int)
print(scores_int)

如果有人能帮助我解决我目前的问题,我将不胜感激。谢谢。

【问题讨论】:

    标签: python-2.7 csv int bubble-sort


    【解决方案1】:

    如果 csv 文件逐行包含数字,则此代码有效(python 2.7):

     190
     200
     250
     350
     90
    

    【讨论】:

    • 但它没有对数字进行排序
    猜你喜欢
    • 2019-05-18
    • 2014-01-16
    • 2020-03-16
    • 2016-08-25
    • 2017-04-05
    • 2012-07-15
    • 2013-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多