Python 3.x 将列表转换为整数

Python 3.x 将列表转换为整数,python-3.x,string,list,replace,integer,Python 3.x,String,List,Replace,Integer,问题是: 编写一个程序,计算并打印文本文件中数字的平均值。您应该使用两个高阶函数来简化设计 程序输入和输出示例如下所示: 输入输入文件名:numbers.txt 平均为69.83333 以下是numbers.txt中的数字: 45 66 88 1002298 这是我的代码: file = input("Enter the input file name: ") with open(file) as f: from functools import reduce

问题是: 编写一个程序,计算并打印文本文件中数字的平均值。您应该使用两个高阶函数来简化设计

程序输入和输出示例如下所示:

输入输入文件名:numbers.txt

平均为69.83333

以下是numbers.txt中的数字: 45 66 88 1002298

这是我的代码:

    file = input("Enter the input file name: ")
    with open(file) as f:
        from functools import reduce
        def add(x, y): return x + y
        data = [45, 66, 88, 100, 22, 98]
        total = reduce(add, data)
        avg = total / len(data)
        print("The average is: ", avg)

if __name__ == "__main__":
    main()
    file = input("Enter the input file name: ")
    with open(file) as f:
        for line in f:
            line = line.strip()
            data = [line]
        data = list(map(int, data))
        from functools import reduce
        def add(x, y): return x + y
        total = reduce(add, data)
        avg = total / len(data)
        print("The average is: ", avg)

if __name__ == "__main__":
    main()
问题是,当我在列表中手动输入项目时,这可以正常工作,但当我添加line.strip函数并尝试将其放入列表中,然后使用map转换时,我的代码如下:

    file = input("Enter the input file name: ")
    with open(file) as f:
        from functools import reduce
        def add(x, y): return x + y
        data = [45, 66, 88, 100, 22, 98]
        total = reduce(add, data)
        avg = total / len(data)
        print("The average is: ", avg)

if __name__ == "__main__":
    main()
    file = input("Enter the input file name: ")
    with open(file) as f:
        for line in f:
            line = line.strip()
            data = [line]
        data = list(map(int, data))
        from functools import reduce
        def add(x, y): return x + y
        total = reduce(add, data)
        avg = total / len(data)
        print("The average is: ", avg)

if __name__ == "__main__":
    main()
我得到这个错误:

Traceback (most recent call last):
  File "average.py", line 15, in <module>
    main()
  File "average.py", line 7, in main
    data = list(map(int, data))
ValueError: invalid literal for int() with base 10: '100 22 98'
回溯(最近一次呼叫最后一次):
文件“average.py”,第15行,在
main()
文件“average.py”,第7行,在main中
数据=列表(映射(int,data))
ValueError:基数为10的int()的文本无效:“100 22 98”
我在编码方面很糟糕,你能帮我理解1)错误是什么2)列表中没有将字符串转换成整数有什么问题吗


谢谢大家!

您对下面的代码行有问题,这不是拆分行并将每个项目添加到列表中。它将整行作为字符串添加到列表中

data = [line]
e、 g

您需要像下面这样更改代码,它应该可以工作

file = input("Enter the input file name: ")
with open(file) as f:
    for line in f:
        line = line.strip()
        data = line.split()
    data = list(map(int, data))
    from functools import reduce
    def add(x, y): return x + y
    total = reduce(add, data)
    avg = total / len(data)
    print("The average is: ", avg)

更改此行:
data=list(map(int,data))
data=list(map(int,data.split())