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

Python中如何使用pop方法移除列表中userId为5的指定索引条目

错误原因
  • 遍历范围参数错误:你编写的range(len(mylist)-5, -5, -5)实际仅会生成5、0两个索引值,无法覆盖列表全部元素,而userId为5的条目初始位于索引4的位置,自然不会被检查到
  • 遍历列表并删除元素时如果使用正序遍历,会因为删除元素后后续元素索引前移,出现漏判的问题,必须使用倒序遍历全量索引的方式规避该问题
测试代码修正版(强制使用.pop方法实现)
mylist= [{"userId":1}, {"userId":2}, {"userId":3}, {"userId":4}, {"userId":5}, 
         {"userId":6}, {"userId":7}, {"userId":8}, {"userId":9}, {"userId":10}]

# 倒序遍历列表所有索引
for i in range(len(mylist)-1, -1, -1):
    if mylist[i]["userId"] == 5:
        mylist.pop(i)

print(mylist)
整合到JSON读取场景的完整可运行代码

原来的打印语句中f字符串占位符为空的问题也同步修正:

import json
import urllib.request

url = "https://jsonplaceholder.typicode.com/posts"
data = urllib.request.urlopen(url).read().decode()

site_info = json.loads(data)

# 先过滤userId为5的条目
for i in range(len(site_info)-1, -1, -1):
    if site_info[i]["userId"] == 5:
        site_info.pop(i)

# 打印过滤后的结果
for info in site_info:
    print(f"{info['userId']}, {info['id']}, {info['title']}, {info['body']}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 01:09:03