python - 在 Python 中将字符串数据转换为整数
问题描述
我有以下程序从 csv 文件中读取一些数据,但它似乎抵制了所有将“标记”数据读取为整数或稍后将其转换为整数的尝试。我将此程序基于我拥有的另一个功能齐全的程序,唯一真正的区别是整数字段在我的功能程序中是一个浮点数。
我尝试在“for counter...”行之后将以下行输入到 findHighest 函数中。
**Students[0].marks = int(Students[0].marks)**
代码运行但没有找到数据中的最高数字(当最高数字为 100 时返回 96,第二高为 96)。我也尝试过更改以下行...
Students[counter].marks = row[3]
并将其更改为...
**Students[counter].marks = int(row[3])**
这给了我以下错误:
ValueError: int() 以 10 为底的无效文字:''
我在这里想念什么?:-/
导入 csv
class Student:
def __init__(self,forename,surname,form,marks):
self.forename = ""
self.surname = ""
self.form = ""
self.marks = 0
def readFile():
Students = []
filename = "pupils.csv"
csv_file = open(filename, "r")
reader = csv.reader(csv_file)
counter = 0
for row in reader:
Students.append(Student("", "", "", 0))
Students[counter].forename = row[0]
Students[counter].surname = row[1]
Students[counter].form = row[2]
Students[counter].marks = row[3]
counter = counter + 1
return Students
def findHighest(Students):
position=0
highest = Students[0].marks
for counter in range(len(Students)):
Students[counter].marks = int(Students[counter].marks)
if Students[counter].marks > highest:
highest = Students[counter].marks
position = counter
return highest
def displayHighest(highest):
print("the highest pupil score was:", highest)
Students = readFile()
highest = findHighest(Students)
displayHighest(highest)
CSV 文件:
解决方案
我猜你有多个问题
def findHighest(Students):
position=0
#highest is set to a string. You should set highest to 0
highest = Students[0].marks
for counter in range(len(Students)):
#why do you always set Students[0] and not Students[counter]. You always convert Students[0] to int.
Students[0].marks = int(Students[0].marks)
#As a result you always tests string again strings:
if Students[counter].marks > highest:
highest = Students[counter].marks
position = counter
return highest
这次尝试
Students[counter].marks = int(row[3])
应该是正确的,但 ValueError 可能暗示您的 CSV 内容根本不是正确的整数值。请检查您的 CSV 或像这样处理异常: Converting String to Int using try/except in Python
推荐阅读
- python - 在 matplotlib 中绘制 Shapley Multiploygon 的更有效方法
- python - 如何用python批量按键?
- java - Css媒体查询不适用于Spring框架
- excel - VBA for Excel - 按条件复制数据 -
- python - 运行时错误:给定组=721,在维度 0 处的预期权重至少为 721,但得到的权重大小为 [3, 1, 5, 5]
- r - 咕噜声或循环表以自动化绑定行过程
- python - 如何在 dask_cudf 和 cudf 中使用 tqdm 进度条
- c++ - 如何从c ++中的对象数组中删除一条记录
- python - 从字符串中删除特定字符的 Pythonic 方法
- reactjs - 调度一个动作一次,它被渲染两次而不是被渲染一次