【问题标题】:sums.append(map(int, row)) ValueError: invalid literal for int() with base 10: ''sums.append(map(int,row))ValueError:int()的无效文字,底数为10:''
【发布时间】:2016-01-22 07:14:46
【问题描述】:

我正在用 Python 2.7 编写一个小程序,它从文本文件中为每一行读取四个数字并计算每一行的总和

文件.txt:

1 2 4 5
5 5 5 12
3 3 89 21
1 0 5 6 

我的程序:

def CalcSum(a,b,c,d):
    sum = a+b+c+d
    return sum

with open('file.txt', 'r') as i_file:
    reader = i_file.readline()
sums = []
for row in reader:
    sums.append(map(int, row))

for dt in sums:
    dt.append(CalcSum(dt[0], dt[1], dt[2], dt[3]))
print sums
i_file.close()

但是当我朗姆我的程序时,我得到了这个错误:

Traceback(最近一次调用最后一次):文件 “/home/Erick/Desktop/testpy.py”,第 10 行,在 sums.append(map(int, row)) ValueError: int() 以 10 为底的无效文字:''

我该如何解决这个错误? 提前谢谢!!!

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    我认为您可能缺少s

    with open('file.txt', 'r') as i_file:
        reader = i_file.readlines()
    

    然后用

    sums.append(map(int, row))
    

    您将int 应用于文件中的每一行,而不是每个数字。

    在代码的后面还有另一个错误

    for dt in sums:
        dt.append(CalcSum(dt[0], dt[1], dt[2], dt[3]))
    

    将总和附加到找到的每个数字列表中。

    终于

    i_file.close()
    

    不必要地关闭文件,因为它将被with 语句创建的上下文管理器关闭(这正是with 的目的)

    所以,总结一下,这里是完整修复的代码

    def CalcSum(a,b,c,d):
        sum = a+b+c+d
        return sum
    
    with open('file.txt', 'r') as i_file:
        reader = i_file.readlines()
    sums = []
    for row in reader:
        sums.append(map(int, row.split()))
    
    final_sums = []
    for dt in sums:
        final_sums.append(CalcSum(dt[0], dt[1], dt[2], dt[3]))
    print final_sums
    

    为了使它更 Pythonic,让我建议一个替代的、更简洁的整个算法的版本

    with open('file.txt', 'r') as i_file:
        final_sums = [sum(map(int,row.split())) for row in i_file]
    

    如果文件包含:

    1 2 4 5
    5 5 5 12
    3 3 89 21
    1 0 5 6 
    

    final_sums 将举行

    [12, 27, 116, 12]
    

    注意:readlines() 读取内存中文件的全部内容。如果文件很大,会很不方便。 一次读取一行内容更具可扩展性。

    【讨论】:

    • @StefanPochmann 感谢您指出这一点。我默认读过readlines(),也被row这个名字欺骗了
    • 哦,是的,您还有两个错误...我要编辑我的答案
    • 答案现在包含重写的完整代码。我刚刚检查了它,它工作正常。
    猜你喜欢
    • 2017-11-17
    • 2020-10-12
    • 2021-01-07
    • 2018-03-26
    • 1970-01-01
    • 1970-01-01
    • 2021-07-23
    • 1970-01-01
    • 2021-01-10
    相关资源
    最近更新 更多