How to modify list entries during for loop?

前端 未结 9 721
旧巷少年郎
旧巷少年郎 2020-11-22 01:56

Now I know that it is not safe to modify the list during an iterative looping. However, suppose I have a list of strings, and I want to strip the strings themselves. Does re

相关标签:
9条回答
  • 2020-11-22 02:20

    Since the loop below only modifies elements already seen, it would be considered acceptable:

    a = ['a',' b', 'c ', ' d ']
    
    for i, s in enumerate(a):
        a[i] = s.strip()
    
    print(a) # -> ['a', 'b', 'c', 'd']
    

    Which is different from:

    a[:] = [s.strip() for s in a]
    

    in that it doesn't require the creation of a temporary list and an assignment of it to replace the original, although it does require more indexing operations.

    Caution: Although you can modify entries this way, you can't change the number of items in the list without risking the chance of encountering problems.

    Here's an example of what I mean—deleting an entry messes-up the indexing from that point on:

    b = ['a', ' b', 'c ', ' d ']
    
    for i, s in enumerate(b):
        if s.strip() != b[i]:  # leading or trailing whitespace?
            del b[i]
    
    print(b)  # -> ['a', 'c ']  # WRONG!
    

    (The result is wrong because it didn't delete all the items it should have.)

    Update

    Since this is a fairly popular answer, here's how to effectively delete entries "in-place" (even though that's not exactly the question):

    b = ['a',' b', 'c ', ' d ']
    
    b[:] = [entry for entry in b if entry.strip() == entry]
    
    print(b)  # -> ['a']  # CORRECT
    
    0 讨论(0)
  • 2020-11-22 02:24

    It's considered poor form. Use a list comprehension instead, with slice assignment if you need to retain existing references to the list.

    a = [1, 3, 5]
    b = a
    a[:] = [x + 2 for x in a]
    print(b)
    
    0 讨论(0)
  • 2020-11-22 02:24

    The answer given by Jemshit Iskenderov and Ignacio Vazquez-Abrams is really good. It can be further illustrated with this example: imagine that

    a) A list with two vectors is given to you;

    b) you would like to traverse the list and reverse the order of each one of the arrays

    Let's say you have

    v = np.array([1, 2,3,4])
    b = np.array([3,4,6])
    
    for i in [v, b]:
        i = i[::-1]   # this command does not reverse the string
    
    print([v,b])
    

    You will get

    [array([1, 2, 3, 4]), array([3, 4, 6])]
    

    On the other hand, if you do

    v = np.array([1, 2,3,4])
    b = np.array([3,4,6])
    
    for i in [v, b]:
       i[:] = i[::-1]   # this command reverses the string
    
    print([v,b])
    

    The result is

    [array([4, 3, 2, 1]), array([6, 4, 3])]
    
    0 讨论(0)
提交回复
热议问题