Python将我列表中的二维字符串转换为浮点数

2024-04-20 12:18:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个学校的项目,我需要做一个二维列表,并计算该列表上的平均分。出于某种原因,我无法将列表上的值更改为浮点值,甚至认为它可以使用print(pointslist[0][1])将它们打印为单个值。你知道吗

def read_points():

print("Input the points, one per line as x,y.")
print("Stop by entering an empty line.")
arvo = 0
pointslist = []
while arvo != "":
    arvo = input("")
    kordinaatti = arvo.split(",")
    pointslist.append(kordinaatti)

return pointslist   

def calculate_midpoint(pointslist):

h = len(pointslist)
j = int(0)
summax = 0
summay = 0
while j <= h:
    arvox = pointslist[j][0]
    arvoy = pointslist[j][1]
    summax += float(arvox)
    summay += float(arvoy)
    summax = float(summax / h)
    summay = float(summay / h)
    j += 1       
return summax, summay

给出错误:

summax += float(arvox)

ValueError: could not convert string to float: ¨

格式有点错误,但在代码中是正确的。你知道吗

谢谢:)现在我看到了问题,但这部分代码仍然有问题:

def calculate_midpoint(pointslist):

h = len(pointslist)
j = 0
summax = 0
summay = 0
while j <= h:
    arvox = float(pointslist[j][0])
    arvoy = float(pointslist[j][1])
    summax += float(arvox)
    summay += float(arvoy)
    summax = float(summax / h)
    summay = float(summay / h)
    j += 1       
return summax, summay

超出索引。例如,当我插入0而不是J时,代码运行良好。J得到什么值,因为它会使程序崩溃?你知道吗

这个问题已经解决了,多亏你们大家的帮助!!你知道吗


Tags: 列表returndeflinefloatpointsprintwhile
3条回答

这是一个很好的开始,但是代码中有两个错误。你知道吗

第一个错误是读取输入的代码试图将空行视为浮点。你知道吗

第二个错误是,计算中点的代码试图通过在比较中使用less thanequal to来处理列表末尾以外的点。你知道吗

我已经修改了你的代码,使其在下面正常工作。你知道吗

def read_2d_points():
    '''
    Read 2D points from the command line.
    '''
    print("Input the points, one per line as x,y.")
    print("Stop by entering an empty line.")
    arvo = 0
    pointslist = []
    while arvo != "":
        arvo = input("? ")
        if ',' in arvo:
            # Ignore the case where the line is empty
            # to avoid a float conversion error.
            kordinaatti = [float(x.strip()) for x in arvo.split(",")]
            assert len(kordinaatti) == 2  # assume 2D
            pointslist.append(kordinaatti)
    assert len(pointslist) > 1
    return pointslist   


def calculate_midpoint(pointslist):
    '''
    Calculate the mid point.
    '''
    h = len(pointslist)
    j = int(0)
    summax = 0
    summay = 0
    while j < h:
        arvox = pointslist[j][0]
        arvoy = pointslist[j][1]
        summax += float(arvox)
        summay += float(arvoy)
        summax = float(summax / h)
        summay = float(summay / h)
        j += 1       
    return summax, summay

pointsList = read_2d_points()
print('points: {} {}'.format(len(pointsList), pointsList))
print('midpoint: {}'.format(calculate_midpoint(pointsList)))

如果您对扩展python知识感兴趣,我建议您考虑添加错误处理(assert除外),考虑使用classesnamedtuples,并可能考虑使用列表理解。你知道吗

祝你好运。你知道吗

忽略格式问题,底层代码中有两个错误:

read_points

read_points在读取一个空行后终止,但它也将这个空行附加到pointslist,这意味着pointslist中的最后一个条目无效。有很多方法可以解决这个问题:一个简单的方法是在每次迭代结束时而不是开始时阅读:

def read_points():
    print("Input the points, one per line as x,y.")
    print("Stop by entering an empty line.")
    arvo = 0
    pointslist = []
    arvo = input("")
    while arvo != "":
        kordinaatti = arvo.split(",")
        print(kordinaatti)
        pointslist.append(kordinaatti)
        arvo = input("")

    return pointslist

这是导致“无法将字符串转换为浮点”问题的原因,因为最后一个点不是有效点。你知道吗

calculate_midpoint

您的代码从j=0迭代到j=len(pointslist),并在每次迭代时尝试访问pointslist[j]。这试图读取len(pointslist) + 1项,这是不正确的;您最多只能读取j=len(pointslist) - 1。这就是你在评论中提到的索引错误

固定版本:

def calculate_midpoint(pointslist):
    print(pointslist)
    h = len(pointslist)
    j = int(0)
    summax = 0
    summay = 0
    while j < h:
        arvox = pointslist[j][0]
        arvoy = pointslist[j][0]
        summax += float(arvox)
        summay += float(arvoy)
        summax = float(summax / h)
        summay = float(summay / h)
        j += 1
    return summax, summay

您的read_points()正在返回一个值,该值是float无法处理的空字符串。你知道吗

如果执行read_points()并输入'5','4','3',则返回[['5'], ['4'], ['3'], ['']]当尝试float('')时,该列表中的最后一项将抛出错误。所以要么在read_points()中修复它,只返回输入的而不是空行,要么在第二个函数中处理非整数。你知道吗

因此,代码的另一种替代方法可能是:

def read_points():

    print("Input the points, one per line as x,y.")
    print("Stop by entering an empty line.")
    arvo = 0
    pointslist = []
    while arvo != "":
        arvo = input("")
        kordinaatti = arvo.split(",")
        pointslist.append(kordinaatti)

    return pointslist[:-1]   

def calculate_midpoint(pointslist):

    h = len(pointslist)-1
    j = int(0)
    summax = 0
    summay = 0
    while j <= h:
        arvox = pointslist[j][0]
        arvoy = pointslist[j][0]
        summax += float(arvox)
        summay += float(arvoy)
        summax = float(summax / h)
        summay = float(summay / h)
        j += 1       
    return summax, summay

相关问题 更多 >