簡體   English   中英

如何讀取文本文件並轉換為列表以與 Python 中的統計包一起使用

[英]How to read a text file and convert into a list for use with statistics package in Python

我到目前為止運行的代碼如下

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.

我的任務是創建一個程序,顯示該時間段內人口的平均變化。 在此期間人口增長最多的年份。 該時間段內人口增長(與上一年相比)最小的年份。

該代碼將在一行上打印每個文本文件條目,但在嘗試轉換為 int 以與統計包一起使用時,我收到以下錯誤:

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

語法錯誤:無法分配給函數調用

values(index) = int(values(index)) 行取自讀取以及堆棧溢出的資源。

您可以將values = infile.read()更改為values = list(infile.read())並將其輸出為列表而不是字符串。

每當讀取這樣的文件時,往往會發生的一件事是,在每一行的末尾都有一個不可見的'\\n' ,它在文本文件中聲明了一個新行,因此這是一種按行拆分的簡單方法和將它們轉換為整數將是,而不是使用values = list(infile.read())你可以使用values = values.split('\\n')它分割線的基礎,只要先前聲明了values

並且您擁有的 while 循環可以輕松地替換為for循環,您可以在其中使用 len(values) 作為結尾。

values(index) = int(values(index))部分是在 while 循環中執行此操作的不錯方法,但是無論何時在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()

如果您需要對我在代碼中所做的任何事情進行澄清,請詢問。

我個人會使用 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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM