[英]function using dictionary as argument
I have created a dictionary with values for Velocity, temperature and altitude: 我创建了一个字典,其中包含“速度”,“温度”和“高度”的值:
mach_dict = dict(velocity=[], altitude=[], temperature=[])
Which I use to store values for a flying plain at climb, cruise and descent segments. 我用来存储在攀登,巡航和下降段的飞行平原的值。
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]}
I need to create a function (def) that returns a dictionary that stores the mach number for every segment. 我需要创建一个函数(def),该函数返回一个字典,该字典存储每个段的马赫数。
To estimate Mach
I use the formula: 要估算
Mach
我使用以下公式:
Mach = velocity / sqrt(1.4 * 286 * (Temperature - altitude * 0.05))
Can anybody help on that? 有人可以帮忙吗?
You can zip
the list values in the dictionary and compute the new key mach_number
using a list comprehension : 您可以将列表值
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'])]
You'd zip together the 3 lists to produce velocity, altitude, temperature
tuples: 您将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)
Unfortunately, your inputs lead to a ValueError: math domain error
because for some you'd get a negative value for 1.4 * 286 * (temp - alt * 0.05)
. 不幸的是,您的输入导致
ValueError: math domain error
因为对于某些用户,您会得到1.4 * 286 * (temp - alt * 0.05)
的负值。
Technically, this is modifying the passed in dictionary, and the return
is unnecessary. 从技术上讲,这正在修改传入的字典,并且不需要
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
And you can use pandas and numpy to do that as well 您也可以使用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))
This will handle the -ve case that it would give you NaN 这将处理-ve情况,它将为您提供NaN
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.