猿问

通过 Python 函数运行多个输入

我正在通过一个函数运行多个浮点数以生成科学记数法。然而,并不是所有的浮点数都一直被放入(它是随机的),因此会产生一个错误。


输入:


a0,hvt,at,lambd = signify(a0,hvt,at,lambd)

功能:


def signify(*args):

    rst = []


    for arg in args:

        if arg >= 100.0 or arg <= 0.01:

            arg = '{:.2e}'.format(arg)

            rst.append(arg)

    return rst

换句话说,'rst' 并不总是由四个元素组成(感谢 Singh 指出)。


有人愿意为我指出正确的方向吗?


翻阅古今
浏览 146回答 1
1回答

泛舟湖上清波郎朗

我认为你不太明白错误是什么。你能把错误信息贴出来吗?我怀疑你试图分配a0,hvt,at,lambd = signify(a0,hvt,at,lambd)是真正的罪魁祸首,如果从函数返回的“rst”没有 4 个元素怎么办?左侧的语法强制右侧的列表准确地解包为 4 个元素,并ValueError: too many values to unpack (expected 4)在不匹配时引发 a 。尝试result = signify(a0,hvt,at,lambd)检查输出。更新:如果您只想修改 4 项中的一部分,而允许其余项按原样通过,则只需要 else 部分。以下是您如何看待整个过程。def signify(*args):&nbsp; &nbsp; rst = []&nbsp; &nbsp; print(args)&nbsp; &nbsp; for arg in args:&nbsp; &nbsp; &nbsp; &nbsp; if arg >= 100.0 or arg <= 0.01:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; arg = '{:.2e}'.format(arg) #returns a string&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; rst.append(arg)&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; rst.append(arg) #take note that this else statement is the same as the last statement of if block&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; #also note that args going through else block are not "strings" unlike the if block, which gives a string during ".format()"&nbsp; &nbsp; return rst我们可以改进这一点。def signify(*args):&nbsp; &nbsp; rst = []&nbsp; &nbsp; print(args)&nbsp; &nbsp; for arg in args:&nbsp; &nbsp; &nbsp; &nbsp; if arg >= 100.0 or arg <= 0.01:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; arg = '{:.2e}'.format(arg)&nbsp; &nbsp; &nbsp; &nbsp; rst.append(arg) #note that you may want to typecast to string to maintain uniformity.&nbsp; &nbsp; &nbsp; &nbsp; #rst.append(str(arg))&nbsp; &nbsp; return rst但是,这本质上与在所有参数上应用函数相同。我们可以创建一个函数来强调这种“处理 1 个术语”的方法。def signify_single(single_arg):&nbsp; &nbsp; if single_arg >= 100 or single_arg <= 0.01:&nbsp; &nbsp; &nbsp; &nbsp; return '{:.2e}'.format(single_arg)&nbsp; &nbsp; return single_arg #or str(single_arg)a,b,c,d = (signify_single(x) for x in (101,202,303,40))但这让我们意识到这只是一个 if-else 语句。他们不一定是丑陋的。(PS。最后一行是列表理解。)a,b,c,d = ('{:.2e}'.format(x)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (x >= 100 or x <= 0.01)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; else x #or str (x)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for x in (101,202,303,40))这个条件可以稍微调整一下,让我们更清楚地理解。请注意,如果您愿意,也可以将它们写在一行中。a,b,c,d = (x if (0.01 < x < 100) else '{:.2e}'.format(x) for x in (101,202,303,40))您可以使用任何看起来最干净的样式,或者探索并找到更好的东西。只需像这样将其应用于您的案例。a0,hvt,at,lambd = (x if (0.01 < x < 100) else '{:.2e}'.format(x) for x in (a0,hvt,at,lambd))
随时随地看视频慕课网APP

相关分类

Python
我要回答