简体   繁体   中英

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.

To estimate Mach I use the formula:

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 :

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:

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) .

Technically, this is modifying the passed in dictionary, and the return is unnecessary.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM