简单的python for循环文件读取并对内部数据求和与平均值 您所在的位置:网站首页 pycharm怎么求均值 简单的python for循环文件读取并对内部数据求和与平均值

简单的python for循环文件读取并对内部数据求和与平均值

2023-08-11 22:22| 来源: 网络整理| 查看: 265

**以下是两个for循环的文件读取的方法,第二种就比较好的体现python的方便性 要求:文件 data.txt 文件中有多行数据,打开文件,读取数据,并将其转化为列表。统计读取的数据,计算每一行的总和、平均值,在屏幕上输出结果。测试文档下载

```#头一个代码块 python fi = open("data.txt", 'r') for l in fi: l = l.split(',') s = 0.0 n = len(l) for i in range(n): p = l[i].split(":") s = s + eval(p[1]) print("总和是:{},平均值是:{:.2f}".format(s,s/n)) fi.close() ```python # -*- coding:utf-8 -*- ''' This is a python123 file. ''' fi = open("data.txt", 'r') for l in fi: l = l.split(',') s = 0.0 n = len(l) for cours in l: items = cours.split(':') s += eval(items[1]) print("总和是:{},平均值是:{:.2f}".format(s,s/n)) fi.close()

读的文件大概内容大概这样子 Chinese: 90,Math:85,English:95, Physical: 81,Art:85,Chemical:88

注意以上两个for循环的写法,开始都通过fi将每一行的数据放入l中(遇见换行符 \n 的时候结束,所以是每一行)

第二个for循环的话,头一个代码块更接近于c语言中的通过改变列表中指代数据地址的数字来进行,而第二个代码块则是直接将元素从l[0]开始依次放入cours中了,

而Python的for循环本质上就是通过不断调用next()函数实现的,即不断的寻找下一个元素并返回(当然准确的python的文档,里面的解释是The next() function returns the next item from the iterator.)



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有