Python根据输入参数计算结果的实例方法
作者:小妮浅浅 时间:2021-12-15 08:30:45
说明
define function,calculate the input parameters and return the result.
数据存放在 txt 里,为 10 行 10 列的矩阵。
编写一个函数,传入参数:文件路径、第一个数据行列索引、第二个数据行列索引和运算符。
返回计算结果
如果没有传入文件路径,随机生成 10*10 的值的范围在 [6, 66] 之间的随机整数数组存入 txt 以供后续读取数据和测试。
1、导入需要的依赖库和日志输出配置
# -*- 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')
2、生成数据
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")
3、加载数据并计算,返回结果。
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})")
4、传入参数,调用函数。
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://www.py.cn/jishu/jichu/32099.html
标签:Python,输入参数,计算结果
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
SQLServer 存储过程简介与使用方法
2009-07-07 14:06:00
python解析多层json操作示例
2021-06-17 22:59:41
网站如何使用黄金分割布局
2010-11-05 18:34:00
![](https://img.aspxhome.com/file/UploadPic/201011/5/01-29s.jpg)
Python Flask前后端Ajax交互的方法示例
2021-09-07 09:09:21
![](https://img.aspxhome.com/file/2023/0/75230_0s.png)
laravel清除视图缓存的代码
2023-11-24 14:39:39
CSS实例教程:复合型CSS条状图表(下)
2010-01-23 12:52:00
pyspark给dataframe增加新的一列的实现示例
2022-06-13 20:00:19
BootStrap 动态添加验证项和取消验证项的实现方法
2023-08-13 14:17:57
关于mysql与mysqli
2011-02-23 12:03:00
图文详解Python中模块或py文件导入(超详细!)
2023-01-13 01:41:13
![](https://img.aspxhome.com/file/2023/5/90565_0s.png)
javascript基础之数组(Array)对象
2008-06-25 13:32:00
python学习之读取配置文件
2021-05-11 11:42:20
asp函数遍历文件夹代码
2010-06-21 10:38:00
让ASP搭配MYSQL
2009-10-04 20:30:00
Python实现简单状态框架的方法
2022-08-20 14:13:44
浅谈PHP错误类型及屏蔽方法
2023-11-23 10:26:46
oracle 合并查询 事务 sql函数小知识学习
2023-07-13 15:07:28
用Pytorch训练CNN(数据集MNIST,使用GPU的方法)
2021-10-12 23:01:01
PHP预定义变量9大超全局数组用法详解
2023-06-14 10:23:47
python opencv之SIFT算法示例
2023-12-27 21:42:33
![](https://img.aspxhome.com/file/2023/0/65950_0s.png)