在python中,如何更改列表的元素数据类型

In python, how to change the element data type of a list

使用 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))
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.

根据错误消息,我的猜测是当创建 vector 时,它的创建类似于某种 list<Any> 而不是 list<float>。我怎样才能比使用 map 将每个元素都转换为浮动更简单?

您正在传递一个元组列表。 Psycopg 将元组改编为记录。您需要传递列表的列表,因为列表适用于数组:

vector = list(map(lambda x:list(x[2:]),res))