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

使用嵌套列表推导式优化Twitter API关键词搜索遇错求助

问题分析

你的错误根源是修改了userTweets的数据结构:原本userTweets里的每个元素是包含public键的字典(用来存点赞数等信息),但你用嵌套列表推导式后,把每个元素替换成了匹配关键词的列表(比如['Abstimmung']或[]),导致排序时lambda x:x['public']试图用字符串键访问列表,触发TypeError。

解决方案

根据你的需求,分两种情况处理:

情况1:只保留包含任意关键词的推文

如果你的目标是筛选出符合关键词的推文,同时保留原字典结构,用any()判断即可,不要替换原元素:

keywords = ['Abstimmung', 'Steuern','OECD']
# 假设推文文本直接存在tweet变量中,如果是字典的text字段,改成keyword in tweet['text']
userTweets = [tweet for tweet in userTweets if any(keyword in tweet for keyword in keywords)]
# 此时排序正常执行
userTweets.sort(key=lambda x:x['public']['like_count'], reverse=True)

情况2:保留所有推文并记录匹配的关键词

如果需要保留所有推文,同时标记每条推文匹配的关键词,不要覆盖原userTweets,可以给字典新增字段:

keywords = ['Abstimmung', 'Steuern','OECD']
for tweet in userTweets:
    # 同样,根据实际推文文本的位置调整,比如tweet['text']
    tweet['matched_keywords'] = [kw for kw in keywords if kw in tweet]
# 原结构未被破坏,排序正常
userTweets.sort(key=lambda x:x['public']['like_count'], reverse=True)

或者用元组存储推文和匹配关键词,避免修改原字典:

keywords = ['Abstimmung', 'Steuern','OECD']
userTweets_with_matches = [
    (tweet, [kw for kw in keywords if kw in tweet])
    for tweet in userTweets
]
# 排序时取元组第一个元素的like_count
userTweets_with_matches.sort(key=lambda x:x[0]['public']['like_count'], reverse=True)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 11:32:12