博客专区 > 好铁 的博客 > 博客详情
好铁 发表于2年前
  • 发表于 2年前
  • 阅读 231
  • 收藏 0
  • 点赞 1
  • 评论 0


刷leetcode时, 有个移除元素的题

def removeElement(self, nums, val):
        for x in nums[:]:
            if x == val:
        return len(nums)

for 语句中nums如果不加[:], 结果就会出问题.


You need to take a copy of the list and iterate over it first, or the iteration will fail with what may be unexpected results.

For example (depends on what type of list):

for tup in somelist[:]:

An example:

>>> somelist = range(10)
>>> for x in somelist:
...     somelist.remove(x)
>>> somelist
[1, 3, 5, 7, 9]

>>> somelist = range(10)
>>> for x in somelist[:]:
...     somelist.remove(x)
>>> somelist
the second one iterates over a copy of the list. So when you modify the original list, you do not modify the copy that you iterate over


If you need to modify the sequence you are iterating over while inside the loop (for example to duplicate selected items), it is recommended that you first make a copy. Iterating over a sequence does not implicitly make a copy. The slice notation makes this especially convenient:

>>> for w in words[:]:  # Loop over a slice copy of the entire list.
...     if len(w) > 6:
...         words.insert(0, w)
>>> words
['defenestrate', 'cat', 'window', 'defenestrate']


There is a subtlety when the sequence is being modified by the loop (this can only occur for mutable sequences, i.e. lists). An internal counter is used to keep track of which item is used next, and this is incremented on each iteration. When this counter has reached the length of the sequence the loop terminates. This means that if the suite deletes the current (or a previous) item from the sequence, the next item will be skipped (since it gets the index of the current item which has already been treated). Likewise, if the suite inserts an item in the sequence before the current item, the current item will be treated again the next time through the loop. This can lead to nasty bugs that can be avoided by making a temporary copy using a slice of the whole sequence, e.g.,

for x in a[:]:
    if x < 0: a.remove(x)

标签: python
共有 人打赏支持
粉丝 31
博文 258
码字总数 77641
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
* 支付类型