[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
下面这题你知道答案了吗?
假设现在我们定义一个列表a,内容如下:
a = [1,2,3,4,5,6,7,8,9,10]
学习过python基础的都知道,针对列表的操作,python提供了一些内置的函数,比如append、count、extend、pop、insert、remove、reverse等函数,那接下来大家先来一起看一段代码,大家觉得执行后的输出结果是啥呢?
a = [1,2,3,4,5,6,7,8,9,10] for i in a: a.remove(i) print(a)
remove是移除列表元素的方法,那么这段脚本执行后的最终结果是什么呢?
你的答案是否正确呢?
思考了片刻之后,那你是不是觉得,最后输出的是一个空的列表呢?
很显然,最终输出的答案肯定不是一个空的列表,最终输出的结果是:
[2, 4, 6, 8, 10]
是的,你没有看错,最后输出的是:[2, 4, 6, 8, 10]。
那为什么输出的空列表呢?因为在使用for i in a 这样的操作的时候,没遍历一次后,删除a列表中的一个元素后,a列表的值已经发生了变化。
代码运行的过程如下:
第一次循环,删除下标为0的元素后,此时,列表a变为了[2, 3, 4, 5, 6, 7, 8, 9, 10]
第二次循环,删除下表为1的元素,此时列表a中剔除的是元素3,列表a变为了[2, 4, 5, 6, 7, 8, 9, 10],
以此类推,最后执行代码的输出结果是:[2, 4, 6, 8, 10]
怎么解决上述问题呢?
1、将列表a进行copy一份后进行循环遍历删除
for i in a.copy(): a.remove(i) print(a)
或者
for i in a[:]: a.remove(i) print(a)
2、将列表倒序后再遍历删除
for i in a[::-1]: a.remove(i) print(a)
除了遍历列表,在循环遍历其他类型数据的时候也要注意避免采这种坑,今天的分享就到这了,觉得小编写的对你有帮助的话,可以点个赞哟。