【问题标题】:Web2py Python split rows based on true/false from database resultWeb2py Python 根据数据库结果中的真/假拆分行
【发布时间】:2011-08-01 01:50:16
【问题描述】:

我在 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    

所以我可以把它们放在一张桌子上。有任何想法吗?谢谢!

【问题讨论】:

  • 注意,您应该在控制器中进行数据库选择并将结果传递给视图。
  • 我会,但我还在学习web2py,所以我先把实际代码放在页面中,然后当我做对时,将它移到控制器中。不过,谢谢!

标签: python for-loop split web2py


【解决方案1】:

在原始 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 的模板或“视图”语言。我看到 from here 支持 for 循环。

【讨论】:

  • 这正是我需要的,谢谢!不知道为什么我以前不能得到它,但你的代码工作得很好。 (出于某种原因,我一直遇到 Python 循环问题,而不是其他语言。)
猜你喜欢
  • 2012-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-04
相关资源
最近更新 更多