python for循环求和_简单的Python for循环文件读取和求和以及平均内部数据,pythonfor,并,对,与,平均值...

**

以下是两个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.)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值