# Inside amazon.py, write Python code to read in the contents of the textfile 'input.txt', and for each line in input.txt.
# Write out a new line in a new text file output.txt that computes the answer to some operation on a list of numbers.
# If the input.txt file has the following:
# min: 1,2,3,5,6
# max: 1,2,3,5,6
# avg: 1,2,3,5,6
# Your program should generate an output.txt file as following:
# The min of [1, 2, 3, 5, 6] is 1
# The max of [1, 2, 3, 5, 6] is 6
# The avg of [1, 2, 3, 5, 6] is 3.4
# Assume that the only operations given in the input file are 'min', 'max' and 'avg', and that the operation is always followed by a list of comma separated integers.
# Your program should handle any combination of operations, any lengths of input numbers. You can assume that the list of input numbers are always valid ints, and is never empty.
我尝试单独阅读所有行。然后分别正确地写出它们。到目前为止,我已经尝试过分行并将行放入自己的字段中……我只是迷路了。
file = open("input.txt","r", encoding='utf8')
data = ""
for line in file:
#Let's split the line into an array called "fields" using the " " as a separator:
fields = line.split(":")
#and let's extract the data:
Min = fields[0]
Max = fields[1]
Avg = fields[2]
data += "\t" + Min + "\n" + "\t" + str(Max) + "\n" + "\t" + Avg
print(data)
file.close()
我希望输出txt文件像这样写它。但是代码应该能够处理任何整数。
# The min of [1, 2, 3, 5, 6] is 1
# The max of [1, 2, 3, 5, 6] is 6
# The avg of [1, 2, 3, 5, 6] is 3.4
答案 0 :(得分:0)
基本上,这应该可行。如果您使用python3,请将()
括号放在print
调用的参数周围,否则可能会抱怨。
import numpy as np
with open( 'input.txt' ) as fin :
text = fin.read()
for line in text.split('\n') :
op, nums = line.split(':')
op = op.strip() # remove possible spaces
nums = map( float, nums.strip().split(',') )
print 'The', op, 'of', nums, 'is',
if op == 'avg' :
print np.mean(nums)
elif op == 'min' :
print min(nums)
elif op == 'max' :
print max(nums)
else :
print 'wrong operation'