Python - 如何强制枚举从1开始 - 或解决方法?

时间:2021-09-17 19:44:03

I have a simple for loop:

我有一个简单的for循环:

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:

我希望在每第3个项目之后启动一个新的wx水平boxsizer来创建一个面板,每个面板包含3个节点,并继续与节点中的节点一样多。显而易见的解决方案是:

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:

但是枚举从0开始,所以0%3 == 0并且它会立即开始一个新的行。我试过了:

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.

但当然这不起作用,因为它创建一个新的var而不是更改原始 - 所以我得到1,1,2,3,4等,这将无法工作,因为我会得到4个节点之前我点击指数%3 == 0。

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

有关如何做到这一点的任何建议?这不是一个很大的枚举,通常只有大约10-15项。谢谢。

2 个解决方案

#1


17  

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

从Python 2.6开始,enumerate()接受一个可选的start参数来指示枚举的起始位置。请参阅枚举文档。

#2


3  

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.

这在第二个元素(实际上是第三个元素)之后添加了间隔物,并且在它之后添加了第三个元素。

#1


17  

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

从Python 2.6开始,enumerate()接受一个可选的start参数来指示枚举的起始位置。请参阅枚举文档。

#2


3  

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.

这在第二个元素(实际上是第三个元素)之后添加了间隔物,并且在它之后添加了第三个元素。