使用字典作为参数的函数

2024-09-30 14:38:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个字典,里面有速度、温度和高度的值:

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

有人能帮忙吗?你知道吗


Tags: 函数字典高度defsqrt温度速度dict
3条回答

您可以将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)的负值。你知道吗

您可以zip字典中的列表值,并使用列表理解计算新键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'])]

从技术上讲,这是在修改传入的字典,而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

相关问题 更多 >