在python中,如何更改列表的元素数据类型
使用python3.4.3和psycopg2 我有以下SQL查询在python中,如何更改列表的元素数据类型,python,python-3.x,psycopg2,Python,Python 3.x,Psycopg2,使用python3.4.3和psycopg2 我有以下SQL查询 SELECT somestring1, somestring2, float1, float2, float3 FROM table 我想将float1、float2、float3合并成一个float[],然后使用UPDATE将其返回到数据库,因此我编写以下代码: res = cur.fetchall() date = list(map(lambda x: x[0],res)) c
SELECT
somestring1,
somestring2,
float1,
float2,
float3
FROM
table
我想将float1、float2、float3合并成一个float[],然后使用UPDATE
将其返回到数据库,因此我编写以下代码:
res = cur.fetchall()
date = list(map(lambda x: x[0],res))
code = list(map(lambda x: x[1], res))
#vector = list(map(lambda x: list(map(float,x[2:])), res)) # this one works
vector = list(map(lambda x:x[2:],res)) # which won't work
res = list(zip(vector,date,code))
cur.executemany("""
UPDATE mapped SET
vector = %s
WHERE
date = %s AND
code = %s
""",res) # error occurs here
错误消息:
psycopg2.ProgrammingError: column "vector" is of type double precision[] but expression is of type record
LINE 3: vector = (16.25, 15.56, 16.07, 133.409279, 15.35...
^
HINT: You will need to rewrite or cast the expression.
从错误消息中,我猜测当创建
向量时,它的创建类似于某种列表
,而不是列表
。我怎么做才能比使用map
将每个元素强制转换为浮动更简单呢?您正在传递一个元组列表。元组由Psycopg调整为记录。当列表适应于数组时,需要传递列表列表:
vector = list(map(lambda x:list(x[2:]),res))
map返回python中的map对象3@Moses谢谢,修好了。