无法在python中将字符串元组转换为常规元组



我有一个使用psycopg2获得的数据库选择输出。输出看起来低于

result = [('("",Loc,001)',), ('(London,Loc,002)',), ('(Tokyo,Loc,006)',), ('("New York","New Loc",TEST2)',), ('(Berlin,Loc,TEST1)',), ('(Dubai,Loc,TEST4)',)]

这个输出是针对我在多个列上运行的一个不同的查询获得的,类似于

SELECT distinct(col1, col2, col3) from table;

但是处理输出非常复杂,因为每个元组中的一些字符串没有引号。

我试着做一些低于的事情

import ast
formatted_result = [item[0] for item in result]
print(ast.literal_eval(formatted_result))

但它抛出以下错误

Traceback (most recent call last):
File "test.py", line 3, in <module>
print(ast.literal_eval(formatted_result))
File "/usr/lib/python2.7/ast.py", line 80, in literal_eval
return _convert(node_or_string)
File "/usr/lib/python2.7/ast.py", line 79, in _convert
raise ValueError('malformed string')
ValueError: malformed string

另一个选项是遍历每个元组,用逗号分隔,并删除不必要的字符,如下面的字符

for item in formatted_result:
col1 = item.split(",")[0].replace('(', "").replace( ")", "").replace('"', "")
col2 = item.split(",")[1].replace('(', "").replace( ")", "").replace('"', "")
col3 = item.split(",")[2].replace('(', "").replace( ")", "").replace('"', "")

处理此输出的正确方法是什么?

在列周围使用括号将返回row-construct,这就是为什么您的输出看起来很糟糕的原因。

query = "select distinct(ts, popularity) from table where id < 28050"
cur.execute(query)
print(cur.fetchall())
>>> [('(1640082115,23)',), ('(1640082115,28)',), ...]

而没有括号的相同查询将返回预期结果:

query = "select distinct ts, popularity from table where id < 28050"
cur.execute(query)
print(cur.fetchall())
>>> [(1640082115, 23), (1640082115, 28), (1640082116, 51), ...]

最新更新