How to modify list entries during for loop?

前端 未结 9 728
旧巷少年郎
旧巷少年郎 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: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']

提交回复
热议问题