Python for loop skipping every other value

后端 未结 2 1368
醉话见心
醉话见心 2021-01-23 15:59

I have run into an odd problem in my django application where a for loop is skipping every other item. I have take a returned queryset and list()ed to iterate over.

相关标签:
2条回答
  • 2021-01-23 16:24

    temp and items refer to the same object, so when you do items.remove() you're also modifying temp. You probably want to do temp = items[:] to copy the values of the items list.

    0 讨论(0)
  • 2021-01-23 16:36

    You should not be modifying a data structure while iterating over it.

    Anyways, this is a more concise and performant code to do your operation:

    items = list(listobj.getItems())
    rendered = set((int(i) for i in request.POST['rendered'].split(',')))
    unrendered = [item for item in items if item.id not in rendered]
    
    0 讨论(0)
提交回复
热议问题