繁体   English   中英

如何操作列表中文本文件中的元素?

[英]How can I manipulate elements from text file in a list?

所以我制作了一个从文本文件中提取信息的代码。 它包含给定月份的温度,并且应该将其存储在列表中。 当我打印它时,它是正确的。 此外,我需要实际使用这些提取的数字来计算平均值、最大值和最小值等......但它不起作用。 我得到 TypeError: unsupported operand type(s) for +: 'int' and 'list' 例如:

sum(oct_1945)/len(oct_1945)

还:

mean_1945=np.mean(oct_1945)

但我只是得到:

TypeError: unsupported operand type(s) for /: 'list' and 'int'

TypeError: unsupported operand type(s) for +: 'int' and 'list'

我的完整代码和打印语句如下:

#xtract data for 1945 temperatures
def extract_data(temp_oct_1945):
    infile = open('temp_oct_1945.txt', 'r') #Open temps for 1945
    infile.readline() #skip first line
    oct_1945=[] #empty ist for temps
    for line in infile:
        numbers=line.split()
        oct_1945.append(numbers)
    infile.close()
    return oct_1945

oct_1945=extract_data('temp_oct_1945.txt')#define oct_1945


def extract_data(temp_oct_2014):
    infile = open('temp_oct_2014.txt', 'r') #Open temps for 2014
    infile.readline() #skip first line
    oct_2014=[] #empty ist for temps
    for line in infile:
        numbers=line.split()
        oct_2014.append(numbers)
    infile.close()
    return oct_2014

oct_2014=extract_data('temp_oct_2014.txt')#define oct_1945

#print statements
"""
1945 temperatures [['7.2', '8.1', '8.9', '11.6', '7.7', '8.7', '6.9'], 
                   ['5.4', '8.8', '8.9', '3.7', '3.3', '5.2', '9.6'], 
                   ['10.8', '5.0', '5.4', '9.5', '5.3', '5.8', '2.3'], 
                   ['4.1', '6.6', '8.2', '6.1', '8.9', '6.6', '4.1'], 
                   ['2.8', '2.1', '4.1']]
2014 temperatures [['9.8', '11.6', '11.5', '13.3', '12.6', '10.3', '7.5'], 
                   ['9.3', '10.3', '10.3', '8.4', '8.8', '5.0', '5.8'], 
                   ['6.8', '2.3', '3.5', '7.9', '11.8', '10.7', '9.0'], 
                   ['5.8', '6.8', '11.7', '10.6', '11.7', '13.1', '13.6'],
                   ['8.0', '3.5', '3.2']]
"""

首先,您有两个基本相同且名称相同的函数。 我们可以做的是有一个函数,我们将文件名传递给它。 我们所做的是将数字作为每行的字符串列表读取,然后将它们连接在一起并将列表的所有条目映射到浮点数并返回结果列表。

def extract_data(filename):
    infile = open(filename, 'r')  # open file
    infile.readline()  # skip first line
    numbers = []  # stores numbers as strings 
    for line in infile:
        numbers += line.split()
    infile.close()
    return list(map(float, numbers))
    
 print(extract_data('temp_oct_1945.txt'))
 print(extract_data('temp_oct_2014.txt'))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM