Web2py Python根据数据库结果的真/假拆分行
我在web2py/python中有以下代码:
{{for row in db(db.t_problems.id==db.t_problems(request.args(0))).select(): }}
这段代码可以抓取到我需要的所有行。这些行实际上是python的结果,当我把它们打印出来时是这样的:
>>> testFunction(2, 3, 4) True >>> testFunction(2, 1, 4) False >>> legalTriangles(-1, -1, -1) False
(当你进行原始输出时,你会得到这样的结果:)
>>> testFunction(2, 3, 4)\r\nTrue >>> testFunction(2, 1, 4)\r\nFalse >>> legalTriangles(-1, -1, -1)\r\nFalse
我需要做的是去掉前面的>>>,把testFunction(X,Y,Z)放到一个变量里,而把True/False放到另一个变量里。我以为这样做可以实现,但这个循环只去掉了\r\n,并没有把它们放到新的变量中去处理:
ios = row.f_tests.split('>>>') #results are now the testFunctions without the >>>
for io in ios:
i = io.split("\r\n")
所以结果变成了:
testFunction(2, 3, 4)True testFunction(2, 1, 4)False testFunction(-1, -1, -1)False
但我真正需要的是……
func1 = testFunction(2, 3, 4)
res1 = True
func2 = testFunction(2, 1, 4)
res2 = False
这样我才能把它们放到一个表格里。有什么想法吗?谢谢!
1 个回答
0
在原生的Python中,代码会是这样的:
s = ">>> testFunction(2, 3, 4)\r\nTrue >>> testFunction(2, 1, 4)\r\nFalse >>> legalTriangles(-1, -1, -1)\r\nFalse"
for func, result in [i.splitlines() for i in s.split(">>>") if i]:
print "<tr><td>%s</td><td>%s</td></tr>" % (func.strip(), result.strip())
结果是:
<tr><td>testFunction(2, 3, 4)</td><td>True</td></tr>
<tr><td>testFunction(2, 1, 4)</td><td>False</td></tr>
<tr><td>legalTriangles(-1, -1, -1)</td><td>False</td></tr>
你应该能够把它转换成web2py的模板或“视图”语言。我看到这里提到它支持for循环。