【问题标题】:Reading numbers from file and normalizing从文件中读取数字并规范化
【发布时间】:2015-11-04 22:14:15
【问题描述】:

大家好, 我想将我拥有的数据加载到一个文件中,如下所示:

21.4,0.266667,0,0.966667,0.166667,0.966667,0.533333,0.1,............... 

现在,我想从文件中加载它并计算归一化。我愿意:

f = open("Input.txt", "r") 
data = [line.strip() for line in f]
print data
norm = [float(i)/sum(data) for i in data]
print norm

但是,我得到了错误:

ValueError: invalid literal for float()

虽然,我在 linux 中直接在 python 2.7 控制台中执行该过程,

a = [21.4,0.266667,0,0.966667,0.166667,0.966667,0.533333,0.1]
norm = [float(i)/sum(a) for i in a]
print norm

这很好用。我不知道我做错了什么。请帮助我,我是编程新手。提前致谢!

【问题讨论】:

    标签: linux file python-2.7 compiler-errors


    【解决方案1】:

    您需要先将文件中的字符串转换为浮点数。

    data = []
    with open('Input.txt') as f:
        for line in f:
            data.extend([float(x) for x in line.split(',')])
    
    norm = [x/sum(data) for x in data]
    

    【讨论】:

    • 是的,我一直在努力,但你先到了 :)
    • 非常感谢您的意见 :)
    猜你喜欢
    • 2015-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-27
    相关资源
    最近更新 更多