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

Python筛选列表中净粉丝数大于0的字典元素问题求解

问题解决方法

你的代码逻辑偏差出在追加到结果列表的对象上:你仅提取了符合条件字典的first_name字段存入列表,自然只能输出名字列表,改为追加完整的字典对象即可满足需求。

方案1:基于原有代码修改

empty_list = []
for ducks in duck_collection:
    current_trend = ducks['followers'] - ducks['following']
    if current_trend > 0:
        # 改为追加完整的字典对象,而非仅提取first_name字段
        empty_list.append(ducks)
print(empty_list)

方案2:更简洁的列表推导式写法

同等逻辑可以用Python列表推导式一行实现,代码更精简:

result = [duck for duck in duck_collection if duck['followers'] - duck['following'] > 0]
print(result)

两种写法的输出结果都和你预期的完整字典列表一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 03:06:01