【问题标题】:Converting strings in a list to integers python将列表中的字符串转换为整数python
【发布时间】:2017-07-30 17:51:25
【问题描述】:

我正在尝试打开一个 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 = list(r) 应改为scores = [[int(x) if x.isdigit() else x for x in row] for row in r]

标签: python-2.7 csv int converter bubble-sort


【解决方案1】:

您需要添加 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)

【讨论】:

  • 当我添加时,我收到错误消息“TypeError:int() 参数必须是字符串或数字,而不是 'list'”
  • 尝试 scores_int = [int(score[0]) for score in scores]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
  • 2015-01-14
  • 2021-06-18
  • 1970-01-01
  • 2014-07-10
相关资源
最近更新 更多