Python 2.7 Python 2.7:索引器:列表索引超出范围
我试图打开一个csv文件,并将值从字符串转换为整数,以便对列表进行排序。我收到的结果是: “[[]、['190']、['200']、['250']、['350']、['90']]” 这是我的原始代码Python 2.7 Python 2.7:索引器:列表索引超出范围,python-2.7,csv,int,bubble-sort,Python 2.7,Csv,Int,Bubble Sort,我试图打开一个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+
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:列表索引超出范围”
以下是我正在使用的代码的当前版本:
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)
如果有人能帮我解决目前的问题,我将不胜感激。谢谢。如果csv文件逐行包含数字,则此代码正常工作(python 2.7),如下所示:
190
200
250
350
90
但它没有对数字进行排序