Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:将文件中的整数逐行相加_Python_Python 3.x - Fatal编程技术网

Python:将文件中的整数逐行相加

Python:将文件中的整数逐行相加,python,python-3.x,Python,Python 3.x,我希望我的程序计算出一些数字的平均值,这些数字存储在.txt文件Integers.txt中。总共有98个数字,每个数字占1行。我怎样才能算出平均值,称之为“平均长度”。 下面代码中的所有内容都是有效的,只是我正在努力找到一种方法,将它们相加,然后除以它们的数量(平均值) 这是我的代码: def AddSongLengths(): conn = sqlite3.connect("xxxxx.db") c=conn.cursor() PlaylistInput = input

我希望我的程序计算出一些数字的平均值,这些数字存储在.txt文件
Integers.txt
中。总共有98个数字,每个数字占1行。我怎样才能算出平均值,称之为“平均长度”。 下面代码中的所有内容都是有效的,只是我正在努力找到一种方法,将它们相加,然后除以它们的数量(平均值)

这是我的代码:

def AddSongLengths():
    conn = sqlite3.connect("xxxxx.db")
    c=conn.cursor()
    PlaylistInput = input("Select which Playlist you want to calculate the mean of: ")
    Length = c.execute('SELECT "Length" FROM {0}'.format(PlaylistInput))
    file=open("Integers.txt", "w")
    for row in c.fetchall():
        TrackSeconds = TrackIntoSeconds("{0}".format(row[0]))
        file.writelines("""
        {0}""".format(TrackSeconds))
    file.close()

所以你想计算一系列整数的平均值,然后把它们附加到一个文件中

def AddSongLengths():
    conn = sqlite3.connect("xxxxx.db")
    c=conn.cursor()
    PlaylistInput = input("Select which Playlist you want to calculate the mean of: ")
    Length = c.execute('SELECT "Length" FROM {0}'.format(PlaylistInput))
    file=open("Integers.txt", "w")
    sum = 0
    count = 0
    for row in c.fetchall():
        TrackSeconds = TrackIntoSeconds("{0}".format(row[0]))
        file.writelines("""
        {0}""".format(TrackSeconds))
        try:
            sum += int(row[0])
            count += 1
    avg = sum / count
    file.writelines("{}".format(avg))
    file.close()

这应该是可行的——可能需要一些调试:)

先研究,然后发布。有许多问题和教程将向您展示如何获取数字序列的平均值。