You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中基于另一列表过滤元素 按时间戳分组字典

解决方案

报错原因

原代码逻辑写反了成员判断关系:你是要判断timestamp的年月前缀是否在group1列表内,而非判断整个group1列表是否在timestamp字符串中,因此触发类型错误。

方案1:基于原有逻辑修复(固定2020年场景)

把group1改为集合(in查询效率远高于列表,数据量越大优势越明显),提取timestamp前7位的年月前缀做判断即可。
如果按你需求的上半年为1-7月,需要把'2020-07'也加入group1中:

# 集合查询时间复杂度O(1),列表为O(n)
group1 = {'2020-01', '2020-02', '2020-03', '2020-04', '2020-05', '2020-06', '2020-07'}

data = [
    {
        'timestamp': '2020-01-01T00:00:00Z',
        'price': 7204.54,
        'volume_24h': 13086960135,
        'market_cap': 130644686531},
    {
        'timestamp': '2020-01-01T01:00:00Z',
        'price': 7218.55,
        'volume_24h': 13133228186,
        'market_cap': 130899528700},
    {
        'timestamp': '2020-01-01T02:00:00Z',
        'price': 7241.8,
        'volume_24h': 13257849556,
        'market_cap': 131321418482
    }
]

semester_1 = [i for i in data if i['timestamp'][:7] in group1]
semester_2 = [i for i in data if i['timestamp'][:7] not in group1]

方案2:通用跨年份方案(最高效,无需预定义年月)

无需提前维护年份列表,直接提取时间戳中的月份数值判断,且仅需遍历一次数据即可同时分出上下半年,比两次列表推导式少走一遍循环,性能最优:

semester_1 = []
semester_2 = []
for item in data:
    # 固定格式的timestamp中,第5到第7位为月份,转整数直接判断
    month = int(item['timestamp'][5:7])
    # 上半年1-7月,下半年8-12月
    if month <=7:
        semester_1.append(item)
    else:
        semester_2.append(item)

内容的提问来源于stack exchange,提问作者Florent

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 21:39:01