我有两个数组:
a = [0.001,0.01,0.1,1]
h = [2,4,8,16,32,64]
Run Code Online (Sandbox Code Playgroud)
我想创建一个字典,这里的字典键的值的元组a,并h和字典的值是一个空列表.但是,我需要这样做的方式是每个唯一a值都h包含所需的输出:
d = {(0.001,2):[], (0.001,4):[], (0.001,8):[], (0.001,16):[], (0.001,32):[], (0.001,64):[],
(0.01,2):[], (0.01,4):[], (0.01,8):[], (0.01,16):[], (0.01,32):[], (0.01,64):[],
(0.1,2):[], (0.1,4):[], (0.1,8):[], (0.1,16):[], (0.1,32):[], (0.1,64):[],
(1,2):[], (1,4):[], (1,8):[], (1,16):[], (1,32):[], (1,64):[]}
Run Code Online (Sandbox Code Playgroud)
问题是,如上所述,手动编写它是单调乏味的.
无论如何要使用zip或列出理解吗?提前致谢
我希望我的程序的用户以numpy表示法输入他们选择的数学函数,以便我可以对它进行操作.例如:
import numpy as np
f=eval(input("Please input your function in numpy notation")
>>> "Please input your function in numpy notation"
>>> np.exp(x)
>>> NameError: name 'x' is not defined
Run Code Online (Sandbox Code Playgroud)
使用上面的代码,用户输入指数函数,该函数保存到变量'f' - 更一般地说,我希望任何数学函数都作为输入给出,并且它以某种方式存储为python函数.伪代码可能是这样的:
def F(x):
f = eval(input("Please enter function in numpy notation:"))
return f
Run Code Online (Sandbox Code Playgroud)
如果我们再次使用指数函数作为例子,它将等同于硬编码:
def F(x):
return np.exp(x)
Run Code Online (Sandbox Code Playgroud)
为清晰起见,还有一个例子
def F(x):
f = eval(input("Please enter function in numpy notation:"))
return f
>>> x*np.sin(x)
Run Code Online (Sandbox Code Playgroud)
用户在命令行输入x*np.sin(x),相当于硬编码:
def F(x):
return x*np.sin(x)
Run Code Online (Sandbox Code Playgroud)
反正有没有这样做?
假设我有一个返回多个值的函数
import numpy as np
def add_and_raisepower(x, y):
"""
1) Add inputs **x** and **y** and return the result.
2) Raise **x** to the power of **y**, multiply this
result by an array of one's and return the result.
:type x: float
:param x: The first input number
:type y: float
:param y: The second input number
:rtype val1: float
:rtype val2: numpy.array(float)
"""
val1 = x + y
val2 = np.ones(100)*(x**y)
return val1, val2
Run Code Online (Sandbox Code Playgroud)
我关心的是:rtype:文档字符串中的评论;如果函数返回多个值(如本示例所示),则应如何:rtype:在文档字符串中编写(根据 …
a = [['df','37s',''],['4d','34','jd']]
for lst in a:
if any(i=='' for i in lst):
print(lst.index(i)) # NameError: name 'i' is not defined
Run Code Online (Sandbox Code Playgroud)
上面的代码表明了我想要做的事情.
是否有可能得到指数i的lst中传回真正的any()方法,避免过度使用一个明确的for循环lst,如果又如何?