本文摘自php中文网,作者V,侵删。

思路:
接收输入的字符串,以空格为分隔符,将分割的数据存入列表(lst1)中,将lst1中的数据转存入另一个空列表(lst)中,转存时将字符串转化为整型,从而利用函数求出lst中数的和、平均值。
实例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | print ( "-----求平均值,可输入任意多个数-------" )
lst = [] #定义一个空列表
str = raw_input( "请输入数值,用空格隔开:" )
lst1 = str.split( " " )#lst1用来存储输入的字符串,用空格分割
i = 0
while i <= len(lst1)+1:
lst.append(int(lst1.pop()))#将lst1的数据转换为整型并赋值给lst
i += 1
# print (lst)
def sum(list):
"对列表的数值求和"
s = 0
for x in list:
s += x
return s
def average(list):
"对列表数据求平均值"
avg = 0
avg = sum(list)/(len(list)*1.0) #调用sum函数求和
return avg
print ( "avg = %f" %average(lst))
|
运行结果:
1 2 3 4 5 | -----求平均值,可输入任意多个数-------
请输入数值,用空格隔开:21 32 45 65
avg = 47.333333
***Repl Closed***
|
推荐教程:python教程
以上就是python实现输入五个数并求平均值的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
Python并发之poolexecutor的介绍(附示例)
Python怎么装request
Python六种数据类型是什么?
Python中fun是什么意思
Python使用opencv进行标定
Python egg怎么安装
Python可迭代对象怎么理解
Python中eval() 与exec() 函数的用法解析
Python简称是什么
Python 实现在txt指定行追加文本的方法
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » python实现输入五个数并求平均值