在c++和python中都试过,都不可取
nums = [1, 2, 3, 4, 5, 6]
for x in nums:
nums.remove(x)
print(nums)
在python中这么写,一开始会以为nums中所有元素都会被删除殆尽,但实则不然,输出为:
[2, 4, 6]
Process finished with exit code 0
原因是你一边删除,nums列表下标也一直在发生变化。
那么怎么修改呢?
修改后的代码如下:
nums = [1, 2, 3, 4, 5, 6]
for x in nums[:]:
nums.remove(x)
print(nums)
输出为:
[]
Process finished with exit code 0
这样就不会出现 上述的那种情况了