将列表中的字符串转换为整数 python

Converting strings in a list to integers python

我正在尝试打开一个 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)

这可能真的很容易解决,但我对 python 还是个新手,所以如果有人能帮我解决这个问题,我将不胜感激。

您需要添加 scores_int = [int(score) for score in scores] 以便将分数列表中的字符串数字转换为 int 数字。您的代码应该如下所示:

导入 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) for score in scores]

    bubbleSort(scores_int)
    print(scores)