简体   繁体   English

我如何设置枚举的增加,取决于条件?

[英]How i can set the increasing of enumerate, that depends on condition?

I have got the following loop^ 我有以下循环^

i = 0
for var in vars:
    if var[ "ID" ] != 0 and var[ "ID" ] & 1:
        print i, var[ "ID" ]
        i += 1      

Can I use enumerate for this loop instead of counter i ? 我可以在此循环中使用enumerate而不是计数器i吗? How i can set the increasing of enumerate, that depends on this condition: if var[ "ID" ] != 0 and var[ "ID" ] & 1: 我如何设置枚举的增加,这取决于以下条件: if var[ "ID" ] != 0 and var[ "ID" ] & 1:

You may use filter : 您可以使用filter

>>> vs = [{'ID': 1}, {'ID': 4}]
>>> for i, v in enumerate(filter(lambda x: x['ID'] & 1, vs)):
...     print i, v
...
0 {'ID': 1}

No, I don't think you can use enumerate to simplify this code (not without thinning vars first, so that enumerate would only apply to elements that match the condition). 不,我认为您不能使用enumerate来简化此代码(不是先不精简vars ,这样enumerate仅适用于符合条件的元素)。

To be honest, I think the code is pretty straightforward as it is. 老实说,我认为代码非常简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM