假设我想生成一个函数,稍后将其合并到一组方程中,用scipy nsolve函数求解.我想创建一个这样的函数:
xi + xi + 1 + xi + 3 = 1
其中变量的数量将取决于组件的数量.例如,如果我有2个组件:
f = lambda x: x[0] + x[1] - 1
Run Code Online (Sandbox Code Playgroud)
为3:
f = lambda x: x[0] + x[1] + x[2] - 1
Run Code Online (Sandbox Code Playgroud)
我将组件指定为要调用的函数的参数中的数组:
def my_func(components):
for component in components:
.....
.....
return f
Run Code Online (Sandbox Code Playgroud)
我不能找到一种方法来做到这一点.我必须能够这样做,因为这个函数和其他函数需要与nsolve一起解决:
x0 = scipy.optimize.fsolve(f, [0, 0, 0, 0 ....])
Run Code Online (Sandbox Code Playgroud)
任何帮助,将不胜感激
谢谢!
由于我不确定哪种方式最好,我将完全解释我要做的事情:
- 我正在尝试生成这两个函数,以便稍后解决:


所以我想创建一个函数teste([组件列表]),它可以返回这两个方程式(Psat(T)是一个我可以根据组件调用的函数,P是一个常量(值= 760)).
例:
teste(['Benzene','Toluene'])
Run Code Online (Sandbox Code Playgroud)
会回来:
x苯:x甲苯= 1
xBenzene Psat ('Benzene')+ xToluene Psat('Toluene')= 760
在致电的情况下:
teste(['Benzene','Toluene','Cumene'])
Run Code Online (Sandbox Code Playgroud)
它会返回:
x苯:x甲苯+ xCumene = …
很快我需要验证是否验证了3个条件,如果没有执行有关失败条件的事情.我知道我可以使用多个if/else语句迭代3个条件,但我想知道是否有更简单,更简洁的方法来完成它.
以更通用的方式:
if condition1 and condition2 and condition3: pass
else: print which condition has failed
Run Code Online (Sandbox Code Playgroud)
对于一个应用案例:
if file_exist("1.txt") and file_exist("2.txt") and file_exist("3.txt"):
pass
else:
#find which condition has failed
#for file of the failed condition
create_file(...)
Run Code Online (Sandbox Code Playgroud)
我不是要解决上面的例子!我的问题是如何找到在单个if/else语句中的一系列条件中未验证哪个条件!
问候
我在python中有一个字典,如下所示,包含大约20个键:
a = { "1": "","2":"","3":""........"20":"" }
Run Code Online (Sandbox Code Playgroud)
要对字典进行排序,我正在执行以下操作:
for key in sorted(a.iterkeys()):
print key
Run Code Online (Sandbox Code Playgroud)
但是它似乎没有保持按键有序.它将导致此输出:
1 11 12 13 14 15 16 17 18 19 2 20 3 4 5 6 7 .....
我在寻找类似的东西:
1 2 3 4 5 6 ....
任何帮助都会被贬低