小数是与数据库数字类型很好匹配的定点数字。它们真的很有用,但如果我不能说服你使用它们。
largest = [float(d[0]) for d in nlargest]
会给
[254.0, 154.0, 244.0, 134.0, 254.0]
甚至更好,因为 cur 是可迭代的
cur.execute("SELECT desiredParams FROM tableOfInterest;")
nlargest = [float(g[0]) for g in heapq.nlargest(5, cur)]
为了让它漂亮
cur.execute("SELECT param FROM tableOfInterest ORDER BY param DESC FIRST 5;")
nlargest = [float(r.param) for r in cur]
或跳过列表构建并执行此操作
cur.execute("SELECT param FROM tableOfInterest ORDER BY param DESC FIRST 5;")
for param, in cur:
stuff_to_do_with_first_5(float(param))
the way to bind that looks good but is really bad (due to pyscopg's mishandling of bind variables). The problem with this is that pysco just % the values into the string and thus hides the ability to inject sql into your string.
cur.execute("SELECT param FROM tableOfInterest ORDER BY param DESC FIRST %s;", (num_results,))
the way that looks bad but is safer then the previous
cur.execute("SELECT param FROM tableOfInterest ORDER BY param DESC FIRST %d;" % num_results)