how to start the forloop.counter from a different index

笑着哭i 提交于 2020-01-07 09:49:21

问题


I have 2 seperate forloops and i am using forloop.counter in bothloops. I want to start the second forloop counter from the ending of first forloop

{% for i in something1 %}
  <tr>
    <td>{{ forloop.counter }}</td>
    <td>i.username</td>
  </tr>
{% endfor %}
{% for j in something2 %}
  <tr>
    <td>{{ forloop.counter }}</td>
    <td>j.username</td>
  </tr>
{% endfor %}

if the first forloop ends at 10 then i want to start the next for loop from 11.plz help


回答1:


I'm not comfortable with Django, so I show a couple of option in plain Python, given the collections:

something1 = [1,2,3,4]
something2 = [1,2,3,4,5,6,7,8,9,10]

You can access objects by index (not the same as database index):

i = 1
for e1 in something1:
  print(e1)
  i += 1

for i2 in range(i,len(something2)):
  print(something2[i2])

Or slice the last collection:

for e1 in something1:
  print(e1)

for e2 in something2[len(something1):-1]:
  print(e2)

Of course, the last collection has to be the longest.




回答2:


Python's slicing features are quite extensive.
the syntax looks like that: SOME_STRING[start:stop:step].
So basically you can use it pretty much however you like.

I wanted to comment it on your comment, but unfortunately I don't have enough rep :)



来源:https://stackoverflow.com/questions/54264957/how-to-start-the-forloop-counter-from-a-different-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!