Python List & for-each access (Find/Replace in built-in list)

前端 未结 3 1768
执笔经年
执笔经年 2021-02-05 03:07

I originally thought Python was a pure pass-by-reference language.

Coming from C/C++ I can\'t help but think about memory management, and it\'s hard to put it out of my

3条回答
  •  暖寄归人
    2021-02-05 03:28

    You could replace something in there by getting the index along with the item.

    >>> foo = ['a', 'b', 'c', 'A', 'B', 'C']
    >>> for index, item in enumerate(foo):
    ...     print(index, item)
    ...
    (0, 'a')
    (1, 'b')
    (2, 'c')
    (3, 'A')
    (4, 'B')
    (5, 'C')
    >>> for index, item in enumerate(foo):
    ...     if item in ('a', 'A'):
    ...         foo[index] = 'replaced!'
    ...
    >>> foo
    ['replaced!', 'b', 'c', 'replaced!', 'B', 'C']
    

    Note that if you want to remove something from the list you have to iterate over a copy of the list, else you will get errors since you're trying to change the size of something you are iterating over. This can be done quite easily with slices.

    Wrong:

    >>> foo = ['a', 'b', 'c', 1, 2, 3]
    >>> for item in foo:
    ...     if isinstance(item, int):
    ...         foo.remove(item)
    ...
    >>> foo 
    ['a', 'b', 'c', 2]
    

    The 2 is still in there because we modified the size of the list as we iterated over it. The correct way would be:

    >>> foo = ['a', 'b', 'c', 1, 2, 3]
    >>> for item in foo[:]:
    ...     if isinstance(item, int):
    ...         foo.remove(item)
    ...
    >>> foo 
    ['a', 'b', 'c']
    

提交回复
热议问题