找回密码
 快速注册
搜索
查看: 31|回复: 0

[Python]计算平均数

[复制链接]

3149

主题

8386

回帖

6万

积分

$\style{scale:11;fill:#eff}꩜$

积分
65391
QQ

显示全部楼层

hbghlyj 发表于 2022-8-3 08:16 |阅读模式


average.py
# Import the sys module for access to stdin and stdout.
import sys

def average(numbers):
	"""averages takes a list of integers as its
argument and returns their average as a float."""

	total = 0
	
	for number in numbers:
		total += int(number)

	return total/float(len(numbers))


for line in sys.stdin:

	# Get the average of the integers
	#  Since we get each line of stdin as
	#  a string, we use split() to give us
	#  a list of the individual words (which
	#  should all be integers).
	avg = average(line.split())

	# Format the output:
	#  Express our average to 2 decimal places, and
	#  also include the original line (for checking)
	output = "%.2f: %s" % (avg, line)

	# Write it to stdout
	sys.stdout.write(output)
Calculate average of a sequence which starts from $-5$, and increments by $2$, and stops before $10$.
seq -s' ' -5 2 10 | python average.py
Generate 10 random integers within 0-1000 and calculate average:
shuf -i 0-1000 -n 10 | tr '\n' ' ' | python average.py
1 (2).png

手机版|悠闲数学娱乐论坛(第3版)

GMT+8, 2025-3-4 15:42

Powered by Discuz!

× 快速回复 返回顶部 返回列表