Python根據(jù)輸入?yún)?shù)計(jì)算結(jié)果的實(shí)例方法
說(shuō)明
define function,calculate the input parameters and return the result.
數(shù)據(jù)存放在 txt 里,為 10 行 10 列的矩陣。
編寫一個(gè)函數(shù),傳入?yún)?shù):文件路徑、第一個(gè)數(shù)據(jù)行列索引、第二個(gè)數(shù)據(jù)行列索引和運(yùn)算符。
返回計(jì)算結(jié)果
如果沒(méi)有傳入文件路徑,隨機(jī)生成 10*10 的值的范圍在 [6, 66] 之間的隨機(jī)整數(shù)數(shù)組存入 txt 以供后續(xù)讀取數(shù)據(jù)和測(cè)試。
1、導(dǎo)入需要的依賴庫(kù)和日志輸出配置# -*- coding: UTF-8 -*-'''@Author :葉庭云@公眾號(hào) :修煉Python@CSDN :https://yetingyun.blog.csdn.net/'''import numpy as npimport logging logging.basicConfig(level=logging.INFO, format=’%(asctime)s - %(levelname)s: %(message)s’)2、生成數(shù)據(jù)
def generate_fake_data(): ''' :params: 無(wú) :return: 無(wú) :function:如果沒(méi)有傳入文件路徑 隨機(jī)生成10*10 值的范圍在[6, 66]之間的隨機(jī)整數(shù)數(shù)組 存入txt以供后續(xù)讀取數(shù)據(jù)和測(cè)試 ''' # 創(chuàng)建一個(gè) 10*10均值為8,標(biāo)準(zhǔn)差為1的正態(tài)分布的隨機(jī)數(shù)數(shù)組 # data = np.random.normal(8, 1, (10, 10)) # 創(chuàng)建一個(gè) 10*10 值的范圍在[6, 66]之間的隨機(jī)整數(shù)數(shù)組 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、加載數(shù)據(jù)并計(jì)算,返回結(jié)果。
def load_data_and_calculate(point1, point2, operation, file='./data/random_data.txt'): ''' :param file: 文件路徑 為缺省參數(shù):在調(diào)用函數(shù)時(shí)可以傳 也可以省去的參數(shù),如果不傳將使用默認(rèn)值測(cè)試 :param point1: 第一個(gè)數(shù)據(jù)的行列索引 元組類型 :param point2: 第二個(gè)數(shù)據(jù)的行列索引 元組類型 :param operation: 運(yùn)算符 :return: 運(yùn)算后的結(jié)果 ''' if file == './data/random_data.txt': # 還是默認(rèn)參數(shù)的話 說(shuō)明沒(méi)有傳入文件路徑generate_fake_data() else:pass data = np.fromfile(file, sep=’t’, dtype=np.float32) # 讀取txt數(shù)據(jù) numpy的fromfile方法 new_data = data.reshape([10, 10]) # (100,)reshape為(10, 10) 10行10列 print(new_data) # 根據(jù)索引獲取到二維數(shù)組中的兩個(gè)數(shù)據(jù) 捕獲可能的索引越界異常 num1, num2 = None, None try:num1 = new_data[point1[0]][point1[1]]num2 = new_data[point2[0]][point2[1]]print(f'根據(jù)行列索引獲取到的兩個(gè)數(shù)為:{num1} {num2}') # 打印查看 except IndexError:logging.info(f'行列索引超出數(shù)據(jù)集邊界,當(dāng)前數(shù)據(jù)集形狀為:{new_data.shape}') # 進(jìn)行運(yùn)算 捕獲可能的異常 try:# eval函數(shù) 返回傳入字符串的表達(dá)式的結(jié)果result = eval(f'{num1}{operation}{num2}')print(f'result: {num1} {operation.strip()} {num2} = {result}n')return result except ZeroDivisionError:logging.error(f'除數(shù)num2不能為零!') except SyntaxError:if operator in [’x’, ’X’]: logging.error(f'乘法運(yùn)算時(shí)請(qǐng)使用 * 代替 {operation}')else: logging.error(f'輸入的運(yùn)算符非法:({operation})')4、傳入?yún)?shù),調(diào)用函數(shù)。
file_path = './data/testData.txt'# 輸入第一個(gè)數(shù)據(jù)行列索引x1, y1 = map(int, input('請(qǐng)輸入第一個(gè)數(shù)據(jù)行列坐標(biāo)(如: 6,8):').split(’,’))# 輸入第二個(gè)數(shù)據(jù)行列索引x2, y2 = map(int, input('請(qǐng)輸入第一個(gè)數(shù)據(jù)行列坐標(biāo)(如: 3,5):').split(’,’))# 輸入運(yùn)算符號(hào)operator = input('請(qǐng)輸入運(yùn)算符(如+、-、*、/、//、%...):') # 傳入實(shí)參my_result = load_data_and_calculate((x1, y1), (x2, y2), operator, file_path)# 保留兩位小數(shù)輸出print('進(jìn)行 {} 運(yùn)算后,結(jié)果為:{:.2f}'.format(operator, my_result))
到此這篇關(guān)于Python根據(jù)輸入?yún)?shù)計(jì)算結(jié)果的實(shí)例方法的文章就介紹到這了,更多相關(guān)Python如何根據(jù)輸入?yún)?shù)計(jì)算結(jié)果內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. idea修改背景顏色樣式的方法2. jsp EL表達(dá)式詳解3. asp知識(shí)整理筆記4(問(wèn)答模式)4. IntelliJ IDEA 統(tǒng)一設(shè)置編碼為utf-8編碼的實(shí)現(xiàn)5. 解決ajax的delete、put方法接收不到參數(shù)的問(wèn)題方法6. chat.asp聊天程序的編寫方法7. Django ORM實(shí)現(xiàn)按天獲取數(shù)據(jù)去重求和例子8. XML入門的常見(jiàn)問(wèn)題(一)9. Jsp中request的3個(gè)基礎(chǔ)實(shí)踐10. 怎樣才能用js生成xmldom對(duì)象,并且在firefox中也實(shí)現(xiàn)xml數(shù)據(jù)島?
