Python之根据输入参数计算结果案例讲解
作者:叶庭云 时间:2022-08-27 07:44:50
一、问题描述
define function,calculate the input parameters and return the result.
数据存放在 txt 里,为 10 行 10 列的矩阵。
编写一个函数,传入参数:文件路径、第一个数据行列索引、第二个数据行列索引和运算符。
返回计算结果
如果没有传入文件路径,随机生成 10*10 的值的范围在 [6, 66] 之间的随机整数数组存入 txt 以供后续读取数据和测试。
二、Python程序
导入需要的依赖库和日志输出配置
# -*- coding: UTF-8 -*-
"""
@Author :叶庭云
@公众号 :修炼Python
@CSDN :https://yetingyun.blog.csdn.net/
"""
import numpy as np
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s: %(message)s')
生成数据
def generate_fake_data():
"""
:params: 无
:return: 无
:function:如果没有传入文件路径 随机生成10*10 值的范围在[6, 66]之间的随机整数数组
存入txt以供后续读取数据和测试
"""
# 创建一个 10*10均值为8,标准差为1的正态分布的随机数数组
# data = np.random.normal(8, 1, (10, 10))
# 创建一个 10*10 值的范围在[6, 66]之间的随机整数数组
data = np.random.randint(6, 66, (10, 10))
print(data)
with open("./data/random_data.txt", "w") as f:
for i in data:
for j in i:
f.write(str(j) + '\t')
f.write("\n")
加载数据并计算,返回结果。
def load_data_and_calculate(point1, point2, operation,
file="./data/random_data.txt"):
"""
:param file: 文件路径 为缺省参数:在调用函数时可以传 也可以省去的参数,如果不传将使用默认值测试
:param point1: 第一个数据的行列索引 元组类型
:param point2: 第二个数据的行列索引 元组类型
:param operation: 运算符
:return: 运算后的结果
"""
if file == "./data/random_data.txt": # 还是默认参数的话 说明没有传入文件路径
generate_fake_data()
else:
pass
data = np.fromfile(file, sep='\t', dtype=np.float32) # 读取txt数据 numpy的fromfile方法
new_data = data.reshape([10, 10]) # (100,)reshape为(10, 10) 10行10列
print(new_data)
# 根据索引获取到二维数组中的两个数据 捕获可能的索引越界异常
num1, num2 = None, None
try:
num1 = new_data[point1[0]][point1[1]]
num2 = new_data[point2[0]][point2[1]]
print(f"根据行列索引获取到的两个数为:{num1} {num2}") # 打印查看
except IndexError:
logging.info(f"行列索引超出数据集边界,当前数据集形状为:{new_data.shape}")
# 进行运算 捕获可能的异常
try:
# eval函数 返回传入字符串的表达式的结果
result = eval(f"{num1}{operation}{num2}")
print(f"result: {num1} {operation.strip()} {num2} = {result}\n")
return result
except ZeroDivisionError:
logging.error(f"除数num2不能为零!")
except SyntaxError:
if operator in ['x', 'X']:
logging.error(f"乘法运算时请使用 * 代替 {operation}")
else:
logging.error(f"输入的运算符非法:({operation})")
传入参数,调用函数。
file_path = "./data/testData.txt"
# 输入第一个数据行列索引
x1, y1 = map(int, input("请输入第一个数据行列坐标(如: 6,8):").split(','))
# 输入第二个数据行列索引
x2, y2 = map(int, input("请输入第一个数据行列坐标(如: 3,5):").split(','))
# 输入运算符号
operator = input("请输入运算符(如+、-、*、/、//、%...):")
# 传入实参
my_result = load_data_and_calculate((x1, y1), (x2, y2), operator, file_path)
# 保留两位小数输出
print("进行 {} 运算后,结果为:{:.2f}".format(operator, my_result))
结果如下:
来源:https://blog.csdn.net/fyfugoyfa/article/details/119106936
标签:Python,封装
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
客户端模板的应用
2007-05-11 16:50:00
ORCAL 临时创建表与删除表
2023-07-12 19:30:05
Python中的函数参数传递问题
2023-09-28 05:38:12
![](https://img.aspxhome.com/file/2023/0/62290_0s.png)
在Linux中通过Python脚本访问mdb数据库的方法
2023-12-18 16:23:14
PHP中获取文件创建日期、修改日期、访问时间的方法
2023-06-11 18:37:15
目前最全的浏览器/CSS选择器兼容性总结(包括Safari 4 beta)
2009-02-26 15:26:00
![](https://img.aspxhome.com/file/UploadPic/20092/26/css-browsers-0-36s.png)
Python中的lambda和apply用法及说明
2023-08-12 14:56:46
jQuery方法扩展:type, toJSON, evalJSON
2009-02-15 12:42:00
不同情况下修复Access数据库的实用方法
2008-11-28 16:18:00
FckEditor配置手册中文教程详细说明
2010-02-28 12:37:00
如何利用SQL Server 2005中的模板参数
2009-01-23 15:02:00
PHP hebrev()函数用法讲解
2023-06-03 12:49:32
![](https://img.aspxhome.com/file/2023/6/55386_0s.png)
asp中日期时间函数介绍
2013-06-01 20:01:03
MySQL数据库的root口令恢复方法总结
2009-08-19 09:03:00
对python pandas 画移动平均线的方法详解
2023-11-16 04:21:33
用XMLHTTP很好的一个例子
2008-04-25 10:25:00
php+Memcached实现简单留言板功能示例
2023-11-15 09:30:02
![](https://img.aspxhome.com/file/2023/0/85820_0s.png)
python利用JMeter测试Tornado的多线程
2022-10-15 12:03:26
![](https://img.aspxhome.com/file/2023/1/68371_0s.jpg)
eWebEditor不支持IE8/IE7的解决方法
2010-02-28 10:27:00
![](https://img.aspxhome.com/file/UploadPic/20102/28/4270100787_166776e513_o-72s.jpg)
Python基于回溯法子集树模板解决野人与传教士问题示例
2023-07-14 04:36:05
![](https://img.aspxhome.com/file/2023/8/60948_0s.jpg)