How to modify list entries during for loop?

前端 未结 9 719
旧巷少年郎
旧巷少年郎 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:00

    Modifying each element while iterating a list is fine, as long as you do not change add/remove elements to list.

    You can use list comprehension:

    l = ['a', ' list', 'of ', ' string ']
    l = [item.strip() for item in l]
    

    or just do the C-style for loop:

    for index, item in enumerate(l):
        l[index] = item.strip()
    
    0 讨论(0)
  • 2020-11-22 02:01

    In short, to do modification on the list while iterating the same list.

    list[:] = ["Modify the list" for each_element in list "Condition Check"]
    

    example:

    list[:] = [list.remove(each_element) for each_element in list if each_element in ["data1", "data2"]]
    
    0 讨论(0)
  • 2020-11-22 02:08

    No you wouldn't alter the "content" of the list, if you could mutate strings that way. But in Python they are not mutable. Any string operation returns a new string.

    If you had a list of objects you knew were mutable, you could do this as long as you don't change the actual contents of the list.

    Thus you will need to do a map of some sort. If you use a generator expression it [the operation] will be done as you iterate and you will save memory.

    0 讨论(0)
  • 2020-11-22 02:14

    One more for loop variant, looks cleaner to me than one with enumerate():

    for idx in range(len(list)):
        list[idx]=... # set a new value
        # some other code which doesn't let you use a list comprehension
    
    0 讨论(0)
  • 2020-11-22 02:15

    It is not clear from your question what the criteria for deciding what strings to remove is, but if you have or can make a list of the strings that you want to remove , you could do the following:

    my_strings = ['a','b','c','d','e']
    undesirable_strings = ['b','d']
    for undesirable_string in undesirable_strings:
        for i in range(my_strings.count(undesirable_string)):
            my_strings.remove(undesirable_string)
    

    which changes my_strings to ['a', 'c', 'e']

    0 讨论(0)
  • 2020-11-22 02:18

    You can do something like this:

    a = [1,2,3,4,5]
    b = [i**2 for i in a]
    

    It's called a list comprehension, to make it easier for you to loop inside a list.

    0 讨论(0)
提交回复
热议问题