Removing coordinates from list on python

This question already has an answer here:

  • How to remove items from a list while iterating? 18 answers

  • You cannot change something while you're iterating it. The results are weird and counter-intuitive, and nearly never what you want. In fact, many collections explicitly disallow this (eg sets and dicts).

    Instead, iterate over a copy (for e in a[:]: ...) or, instead of modifying an existing list, filter it to get a new list containing the items you want ([e for e in a if ...]). Note that in many cases, you don't have to iterate again to filter, just merge the filtering with the generation of the data.

    L2 = []
    for (a,b) in L1:
      if a >= 0 and b >= 0:
        L2.append((a,b))
    
    L1 = L2
    print L1
    

    您可以使用列表理解进行过滤:

    >>> coords =  [(1, 2), (5, 6), (-1, -2), (1, -2)]
    >>> [coord for coord in coords
    ...  if not any(number < 0 for number in coord)]
    [(1, 2), (5, 6)]
    
    链接地址: http://www.djcxy.com/p/18014.html

    上一篇: 我如何使用Python的itertools.groupby()?

    下一篇: 从python列表中删除坐标