3

我正在使用 psycopg2,并运行以下代码:

conn = psycopg2.connect(database = mydb_name, host = mydb_server, user = mydb_uname, password = mydb_pwd)
cur = conn.cursor()
cur.execute("SELECT desiredParams FROM tableOfInterest;")
all_data = cur.fetchall()
nlargest = heapq.nlargest(5, all_data)

这将返回一个带小数的元组列表:

[(Decimal('254.000'),), (Decimal('154.000'),), (Decimal('244.000'),), (Decimal('134.000'),), (Decimal('254.000'),) ]

我怎样才能将其转换为更像:

[254.000、154.000、244.000、134.000、254.000]

?

4

1 回答 1

3

小数是与数据库数字类型很好匹配的定点数字。它们真的很有用,但如果我不能说服你使用它们。

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)
于 2013-03-29T21:10:08.210 回答