如何从文本文件的字符串中找到列表中数字的平均值?

2024-06-26 14:07:07 发布

您现在位置:Python中文网/ 问答频道 /正文

你知道吗我的.txt地址:

AAAAA--[4,2,1,2,4,2,4,5,2,2,1,5,2,4,3,1,1,3,3,5]

BBB--[5,2,1,2,4,5,4,4,1,2,2,2,4,4,4,3,1,2,3,2]

K--[4,1,2,1,2,1,2,5,1,1,1,1,1,4,2,2,1,5,1,3,4,1]

如何生成输出以下内容的代码:(每个字符串中所有数字的平均值)

AAAAA,2.857142857142857

BBB,2.857142857142857

K,2.142857142857143

注意:代码必须适用于包含不同数量/大小列表的任何其他文本文件,因此我不能像str=“AAAAA--[4,2,1,2,4,5,2,2,1,5,2,4,3,1,1,3,3,5]”这样做,然后找到平均值

the_file = "1.txt"

fileRef = open(the_file,"r")      
localList_ofstrings=[]            
for line in fileRef:
    string = line[0:len(line)-1]
    localList_ofstrings.append(string)
    print(string)


Tags: the字符串代码txtstring地址line数字
3条回答

好吧,我有一个非常简单的解决方案。你知道吗

with open('file.txt','r') as f:

    for line in f.readlines():
        try:
            name, l = tuple(line.split(' '))
        except ValueError:
            continue
        name = str.strip(name)
        l = str.strip(l,' []\n')
        l = list(map(int, l.split(',')))
        print("{},{}".format(name, sum(l)/len(l)))

所以请允许我向你解释一下。我所做的就是读取文件,然后用分隔符拆分它们,然后去掉名称中的空白,然后,去掉空白,换行符和第三个括号。然后我按,分割列表元素,然后使用map函数将它们映射到int。如果您不熟悉map,那么您也可以使用列表理解。然后,我简单地计算出平均值并打印出来。

如果您不熟悉map,只要用l = [int(i) for i in l.split(',')]替换该行就可以了。
希望对你有帮助。干杯:)

这是我的解决方案:

import re
from os.path import exists


def calculate(path: str):
    pattern_digit = re.compile(r"\d")
    pattern_alpha = re.compile(r"[A-Za-z]")
    digits = []
    alphas = []
    if exists(path):
     try:
        with open(path) as file:
            string = file.read()
        listed_str = string.splitlines()

        for emp_str in listed_str:
            if emp_str == '':
                listed_str.remove(emp_str)

        for number in range(len(listed_str)):
            digits.append(sum([int(n) for n in pattern_digit.findall(listed_str[number])]))

        for alphabet in range(len(listed_str)):      
          alphas.append(''.join(pattern_alpha.findall(listed_str[alphabet])))
     except FileNotFoundError:
       return "No such file or directory found"


    for p in range(len(alphas)):
        print(f"{alphas[p]}   {digits[p] / len(digits)}")

我知道这有点复杂,但我保证它会按照您的要求工作。

文件中的条目的格式与普通Python词典完全相同,因此您可以将它们视为:

import ast

data = {}
with open(the_file) as f:
    for line in f:
        key, value = line.split(' ')
        data[key.strip()] = ast.literal_eval(value.strip())  # parse data as Python list literal

现在data将是这样一个字典:

{
    'AAA': [4, 2, 1, 2, 4, 2, 4, 4, 5, 2, 2, 1, 5, 2, 4, 3, 1, 1, 3, 3, 5],
    ...
}

我希望这个数据结构能帮助你计算平均值并把它们写回文件

相关问题 更多 >