这里是问题:
从命令行读取(x,y)对的流。修改datatrans1.py脚本,使其从命令行读取(x,y)对的流并将修改后的对(x,f(y))写入文件。新脚本(这里称为datatrans1b.py)的用法应如下所示:
这是命令行输入:python datatrans1b.py tmp.out 1.1 3 2.6 8.3 7 -0.1675
产生输出文件tmp.out:
提示:在for循环中遍历sys.argv数组并使用range函数具有适当的起始索引和增量以下是datatrans1.py原始脚本:
```
import sys, math
try:
infilename = sys.argv[1]
outfilename = sys.argv[2]
except:
print("Usage:", sys.argv[0], "infile outfile")
sys.exit(1)
ifile = open(infilename, 'r') # open file for reading
ofile = open(outfilename, 'w') # open file for writing
def myfunc(y):
if y >= 0.0:
return y ** 5 * math.exp(-y)
else:
return 0.0
```
逐行读取ifile并写出转换后的值:
```
for line in ifile:
pair = line.split()
x = float(pair[0])
y = float(pair[1])
fy = myfunc(y) # transform y value
ofile.write('hello' '%g %12.5e\n' % (x, fy))
ifile.close()
ofile.close()
```
有关如何修改上述代码以正确运行命令行参数并生成带有坐标对的tmp.out文件的任何线索,将非常有帮助
这应该解决问题:
import sys, math
try:
outfilename = sys.argv[1]
except:
print("Usage:", sys.argv[0], "outfile pairs")
sys.exit(1)
ofile = open(outfilename, 'w') # open file for writing
def myfunc(y):
if y >= 0.0:
return y ** 5 * math.exp(-y)
else:
return 0.0
# Loop through y values, using slices to start at position 3
# and get every second value
for i, y in enumerate(sys.argv[3::2]):
# The corresponding x value is the one before the selected y value
x = sys.argv[2:][i*2]
# Call myfunc with y, converting y from string to float.
fy = myfunc(float(y))
# Write output using f-strings
ofile.write(f'({x}, {fy})\n')