How to modify list entries during for loop?

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

提交回复
热议问题