简体   繁体   English

有没有更干净的方法来处理 for 循环中的(连续)独占 if 语句?

[英]Is there a cleaner way to handle (consecutive) exclusive if-statement in for-loop?

I'm new to Python (I've only used C) and I've discovered new loops such as for/else... So I wonder if I'm ignoring a cleaner way to handle this loop:我是 Python 的新手(我只使用过 C)并且我发现了新的循环,例如 for/else ......所以我想知道我是否忽略了一种更干净的方法来处理这个循环:

flag = 0
for i in range (n):
    if not flag and condition:
        statement_1
        flag = 1
    if flag and condition:
        statement_2

I need to keep the for counting, because I know that at least one element will satisfy the condition, so when I find it I'll do statement_1.我需要保留 for 计数,因为我知道至少有一个元素会满足条件,所以当我找到它时我会做 statement_1。 Then if another element will satisfy the condition as well, I'll do statement_2.然后,如果另一个元素也满足条件,我将执行 statement_2。

flag = False  # I prefer booleans
for i in range(n):
    if condition(i):  # We always need it to be True
        if not flag:
            statement(i)
            flag = True
        else:
            statement2(i)

So far this would work, but since you said there is at least one that satisfies the condition到目前为止,这是可行的,但是既然您说至少有一个满足条件

foo = range(n) # any iterable
iterfoo = iter(foo)
initial_value = next(i for i in iterfoo if condition(i))
statement(initial_value)
for i in iterfoo:
    if condition(i):
        statement2(i)

Now these both, (if I'm not missing something) should do the same thing, just in different ways, so it is your choice, although it also saves you 2 lines of code since you wont be doing the first line in your actual code, so I vote for the second snippet :D现在这两者(如果我没有遗漏一些东西)应该做同样的事情,只是方式不同,所以这是你的选择,虽然它也为你节省了 2 行代码,因为你不会在实际中做第一行代码,所以我投票给第二个片段:D

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

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