[英]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.