以下是一个按日期统计细胞数的示例代码:
import datetime
# 创建一个空的细胞数字典,键为日期,值为细胞数
cell_count = {}
# 模拟数据,日期和细胞数
data = [
{'date': '2021-01-01', 'count': 100},
{'date': '2021-01-02', 'count': 150},
{'date': '2021-01-03', 'count': 200},
{'date': '2021-01-02', 'count': 120},
{'date': '2021-01-01', 'count': 80},
]
# 遍历数据,按日期统计细胞数
for item in data:
# 将日期字符串转换为日期对象
date = datetime.datetime.strptime(item['date'], '%Y-%m-%d').date()
# 如果细胞数字典中已经存在该日期,累加细胞数,否则添加新的日期
if date in cell_count:
cell_count[date] += item['count']
else:
cell_count[date] = item['count']
# 打印统计结果
for date, count in cell_count.items():
print(f"{date}: {count}")
这个示例代码首先创建了一个空的细胞数字典cell_count
,然后遍历给定的数据。在遍历过程中,代码将日期字符串转换为日期对象,并判断该日期是否已经存在于细胞数字典中。如果存在,则将该日期对应的细胞数累加;如果不存在,则将该日期及对应的细胞数添加到细胞数字典中。最后,代码打印出按日期统计的细胞数。
上一篇:按日期统计前 5 个值