Python — how to force enumerate to start at 1 — or workaround?

与世无争的帅哥 提交于 2019-12-14 01:26:20

问题


I have a simple for loop:

for index, (key, value) in enumerate(self.addArgs["khzObj"].nodes.items()):

and I want to start a new wx horizontal boxsizer after every 3rd item to create a panel with 3 nodes each and going on for as many as are in nodes. The obvious solution is to do:

if index % 3 == 0: add a horizontal spacer

but the enumerate starts at 0, so 0 % 3 == 0 and it would start a new row right off the bat. I've tried doing:

if index == 0: index = index + 1

but of course that doesn't work because it creates a new var instead of changing the original -- so I get 1, 1, 2, 3, 4, etc and that won't work because I'll get 4 nodes before I hit a index % 3 == 0.

Any suggestions on how to do this? This isn't a big enumerate, usually only about 10-15 items. Thanks.


回答1:


Since Python 2.6, enumerate() takes an optional start parameter to indicate where to start the enumeration. See the documentation for enumerate.




回答2:


You are going to hate this answer for how obvious it is, but you could just do:

if index % 3 == 2: add a horizontal spacer

This adds the spacer after the 2nd element (which is actually the third), and every third element after it.



来源:https://stackoverflow.com/questions/28921405/python-how-to-force-enumerate-to-start-at-1-or-workaround

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