如何读取文本文件并将其转换为列表,以便与Python中的统计数据包一起使用

如何读取文本文件并将其转换为列表,以便与Python中的统计数据包一起使用,python,python-3.7,Python,Python 3.7,到目前为止,我运行的代码如下 import os import math import statistics def main (): infile = open('USPopulation.txt', 'r') values = infile.read() infile.close() index = 0 while index < len(values): values(index) = int(values(index))

到目前为止,我运行的代码如下

import os
import math
import statistics
def main ():
    infile = open('USPopulation.txt', 'r')
    values = infile.read()
    infile.close()
    index = 0
    while index < len(values):
        values(index) = int(values(index))
        index += 1
    print(values)
main()

The text file contains 41 rows of numbers each entered on a single line like so:
151868
153982
156393
158956
161884
165069
168088
etc.
导入操作系统
输入数学
进口统计
defmain():
infle=open('USPopulation.txt','r')
values=infle.read()
infle.close()
索引=0
当指数
我的任务是创建一个程序,显示这段时间内人口的平均变化。在此期间人口增长最大的年份。在此期间人口增长最小的年份(从上一年开始)

代码将在一行上打印每个文本文件条目,但在尝试转换为int以用于统计数据包时,我遇到以下错误:

值(索引)=int(值(索引))

SyntaxError:无法分配给函数调用


values(index)=int(values(index))行是从读取以及堆栈溢出上的资源中获取的

我个人会使用numpy来读取文本文件

在你的情况下,我会这样做:

import numpy as np

def main ():
    infile = np.loadtxt('USPopulation.txt')
    maxpop = np.argmax(infile)
    minpop = np.argmin(infile)
    print(f'maximum population = {maxpop} and minimum population = {minpop}')
main()

您可以将
values=infle.read()
更改为
values=list(infle.read())
它将把它作为列表而不是字符串输出

每当读取像这样的文件时,往往会发生的一件事是,在每一行的末尾都有一个不可见的
'\n'
,它在文本文件中声明了一个新行,因此,一种简单的方法是将其按行拆分并将其转换为整数,而不是使用
values=list(infle.read())
您可以使用
values=values.split('\n')
,只要先前声明了
values
,它就可以分割行的基础

您拥有的while循环可以很容易地替换为一个循环,使用len(值)作为结束

在while循环中,
values(index)=int(values(index))
部分是一种不错的方法,但是无论何时在
for
循环中,您都可以使用
values[i]=int(values[i])
将它们转换为整数,然后
values
成为整数列表

我个人将如何设置它:

import os
import math
import statistics
def main ():
    infile = open('USPopulation.txt', 'r')
    values = infile.read()
    infile.close()
    values = values.split('\n') # Splits based off of lines
    for i in range(0, len(values)) : # loops the length of values and turns each part of values into integers
        values[i] = int(values[i])


    changes = []
    # Use a for loop to get the changes between each number.
    for i in range(0, len(values)-1) : # you put the -1 because there would be an indexing error if you tried to count i+1 while at len(values)
        changes.append(values[i+1] - values[i]) # This will get the difference between the current and the next.

    print('The max change :', max(changes), 'The minimal change :', min(changes)) 
    #And since there is a 'change' for each element of values, meaning if you print both changes and values, you would get the same number of items.
    print('A change of :', max(changes), 'Happened at', values[changes.index(max(changes))]) # changes.index(max(changes)) gets the position of the highest number in changes, and finds what population has the same index (position) as it.
    print('A change of :', min(changes), 'Happened at', values[changes.index(min(changes))]) #pretty much the same as above just with minimum

    # If you wanted to print the second number, you would do values[changes.index(min(changes)) + 1]
main()

如果您需要对我在代码中所做的任何事情进行澄清,请询问。

您可以添加一个分隔符,例如,如果文件中的值用逗号分隔,如:np.loadtxt('USPopulation.txt',delimiter=“,”),请您尝试更清楚地描述一下好吗?我现在正在运行以下代码并收到许多错误:values=values.split('\n')index=0 for x in value:values[index]=int(values[index]),而index