列表中的数学运算 [英] Math operations from a list

查看:95
本文介绍了列表中的数学运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从.txt文件导入了myList(我将数字转换为整数)

I imported myList from a .txt file (I converted the numbers to integers)

from math import *
myList = [100, 'sin', 0, 1]
x = pi

如何为给定的x值调用sin函数?

How would I go about calling the sin function for my given value of x?

myList[1](pi)

我希望这只会返回sin(pi),但不会,因为它只是字符串'sin(x)'

I hoped this would simply return sin(pi), but it does not, because it is just the string 'sin(x)'

推荐答案

不要将函数存储为字符串文字,请存储实际函数.

Do not store functions as string literals, store the actual functions.

>>> from math import sin, exp, log
>>> funcs = [sin, exp, log]
>>> x = 0
>>> funcs[0](x)
0.0
>>> funcs[1](x)
1.0
>>> funcs[2](2.71)
0.9969486348916096

但是,如果您不打算对该功能列表做更多的事情,则可以直接调用它们.

However, if you don't plan to do something more involved with that list of functions, you can just call them directly.

这篇关于列表中的数学运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆