gpt4 book ai didi

Python:按不同值对单列进行分组

转载 作者:行者123 更新时间:2023-12-01 04:33:38 26 4
gpt4 key购买 nike

我有一个像这样的 sqlite 数据库,其中包含列标题和数据:

expiration, title
2015-08-15, example title
2015-08-15, another sample title
2015-08-15, another one
2015-08-16, lorem ipsum
2015-08-16, example

有没有一种方法可以按到期日期进行分组,这样会产生如下结果:

Expiring 2015-08-15
example title
another sample title
another one
Expiring 2015-08-16
lorem ipsum
example

目前这是我所拥有的:

cur.execute("SELECT DISTINCT * FROM expiration WHERE exp BETWEEN date('now','-1 days') AND date('now','+6 days') ORDER BY exp")
sql.commit()
row = cur.fetchall()
for res in row:
msg += res[1] + "\n"
print msg

但它不按日期分组,它只是列出所有标题

最佳答案

你绝对可以在sql中实现这种分组操作,但是如果不深入研究sqlite细节,在python中也可以很容易地进行分组,如下所示:

import itertools as it

cur.execute("SELECT * FROM expiration WHERE exp BETWEEN date('now','-1 days') AND date('now','+6 days') ORDER BY exp")
sql.commit()
row = cur.fetchall()
for i,g in it.groupby(row, key=lambda x: x[0]):
msg += 'Expiring %s%s\n' % (i, '\n\t'.join(x[1] for x in g))
print msg

关于Python:按不同值对单列进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32030146/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com