[英]Get a new dictionary with the same keys using reduce function with a lambda argument
[英]function using dictionary as argument
我創建了一個字典,其中包含“速度”,“溫度”和“高度”的值:
mach_dict = dict(velocity=[], altitude=[], temperature=[])
我用來存儲在攀登,巡航和下降段的飛行平原的值。
mach_dict = {'velocity': [0, 300, 495, 500, 300], 'altitude': [288.15, 288.15, 288.15, 288.15, 288.15], 'temperature': [0, 0, 50, 50, 50]}
我需要創建一個函數(def),該函數返回一個字典,該字典存儲每個段的馬赫數。
要估算Mach
我使用以下公式:
Mach = velocity / sqrt(1.4 * 286 * (Temperature - altitude * 0.05))
有人可以幫忙嗎?
您可以將列表值zip
到字典中,並使用列表 mach_number
來計算新的密鑰mach_number
:
import math
def compute_mach(velocity, altitude, temperature):
return velocity/math.sqrt(1.4*286*(temperature-altitude*0.05))
mach_dict['mach_number'] = [compute_mach(v, a, t) for v, a, t in zip(mach_dict['velocity'],
mach_dict['altitude'],
mach_dict['temperature'])]
您將3個列表壓縮在一起以生成velocity, altitude, temperature
元組:
mach_dict['mach'] = mach_per_section = []
for vel, alt, temp in zip(
mach_dict['velocity'], mach_dict['altitude'], mach_dict['temperature']):
mach = vel / sqrt(1.4 * 286 * (temp - alt * 0.05))
mach_per_section.append(mach)
不幸的是,您的輸入導致ValueError: math domain error
因為對於某些用戶,您會得到1.4 * 286 * (temp - alt * 0.05)
的負值。
從技術上講,這正在修改傳入的字典,並且不需要return
。
from math import sqrt
def func(d):
machs = []
for v, a, t in zip(d['velocity', d['altitude'], d['temperature']):
mach = v / sqrt(1.4 * 286 * (t - a * 0.05))
machs.append(mach)
d['mach'] = machs
return d
您也可以使用pandas和numpy來做到這一點
import pandas as pd
import numpy as np
def compute(mach_dict):
df = pd.DataFrame.from_dict(mach_dict)
r = df.velocity / np.sqrt(1.4 * 286 * (df.temperature - df.altitude * 0.05))
return list(r)
mach_dict={'velocity':[0, 300, 495, 500, 300],'altitude':[288.15, 288.15, 288.15, 288.15, 288.15],'temperature':[0, 0, 50, 50, 50]}
print(compute(mach_dict))
這將處理-ve情況,它將為您提供NaN
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.