Forgot password?
 Create new account
View 112|Reply 0

[Python]计算平均数

[Copy link]

3146

Threads

8493

Posts

610K

Credits

Credits
66158
QQ

Show all posts

hbghlyj Posted at 2022-8-3 08:16:23 |Read mode
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

手机版Mobile version|Leisure Math Forum

2025-4-20 22:07 GMT+8

Powered by Discuz!

× Quick Reply To Top Return to the list