简体   繁体   English

将数据库查询结果从字符串有效转换为元组

[英]Converting database query results from strings to tuples efficiently

I have an sqlite query which returns the following python list of tuples: 我有一个sqlite查询,它返回以下元组的python列表:

[(u'1623,0.0,1651,2.0e-06,1679,5.0e-06,1707,7.0e-06,1735,9.0e-06,1762,1.1e-05,1790,1.4e-05'),
( u'1933,458273.7,1940,460182.6,1947,464019.3,1954,465922.8,1961,467856.0,1968,479385.0')]

Each string here contains a tuple of x,y pairs ieone item is 1623,0.0 The output which I want is: 这里的每个字符串都包含一个x,y对的元组,即一个项目是1623,0.0我想要的输出是:

[(1623,0.0,1651,2.0e-06,1679,5.0e-06,1707,7.0e-06,1735,9.0e-06,1762,1.1e-05,1790,1.4e-05),
(1933,458273.7,1940,460182.6,1947,464019.3,1954,465922.8,1961,467856.0,1968,479385.0)]

Is there an efficient way to perform this translation? 有没有一种有效的方法来执行此翻译?

Maybe it can be performed at the sql level but I dont think so, my query is as follows: 也许它可以在sql级别执行,但我不这么认为,我的查询如下:

select group_concat( COALESCE(timestamp, "")
                     || COALESCE(",", "")
                     || COALESCE(value, "") )
              from table where type='VALUE' group by eventid;

I cant find a way to concatenate more than one column without converting it to a string 我无法找到一种方法来连接多个列而不将其转换为字符串

Don't group in SQL, group in Python and avoid having to serialize then unserialize your values: 不要在SQL中进行分组,在Python中分组并避免必须序列化然后反序列化您的值:

from itertools import groupby
from operator import itemgetter


cursor.execute('''select eventid, timestamp, value from table
                  where type="VALUE" order by eventid''')
for eventid, rows in groupby(cursor, itemgetter(0)):
    print eventid
    for _, timestamp, value in rows:
        print timestamp, value

Use grouping in SQL only when you need to aggregate your data (to sum, calculate averages, count, etc.) not when you need individual rows from the groups for further processing. 仅当您需要聚合数据(总和,计算平均值,计数等)时才使用SQL中的分组,而不是在需要来自组的各个行进行进一步处理时。

If you need your output exactly as described (a tuple with timestamp, value pairs repeated) you can produce that with: 如果您需要完全按照描述的输出(带有时间戳的元组,重复的值对),您可以使用以下内容生成:

from itertools import groupby
from operator import itemgetter

cursor.execute('''select eventid, timestamp, value from table
                  where type="VALUE" order by eventid''')
result = [tuple(chain.from_iterable(r[1:] for r in rows))
          for eventid, rows in groupby(cursor, itemgetter(0))]

eg for every unique eventid produce a tuple consisting of the chained timestamp and value columns. 例如,对于每个唯一的eventid产生一个由链式时间戳和值列组成的元组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM