說明
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))
到此這篇關于Python根據輸入參數計算結果的實例方法的文章就介紹到這了,更多相關Python如何根據輸入參數計算結果內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!