简体   繁体   中英

Execute loop only once if condition is met

I was wondering if there is a pythonic way to write a code equivalent to the one below without defining doSomething as a separate function.

if test:
    for i in s:
        doSomething()
else:
    doSomething()

In particular, I am thinking of the use case where test checks if s exists.

Any suggestions?

You could possibly do this:

for i in (s if test else [False]):
    doSomething()

You want to execute dosomething once if s exists, otherwise len(s) times.

for i in s if test else [0]:
    dosomething()

The iteratable is a ternary expression:

s if test else [0]

The else value can be any sequence of a single element; since you don't actually use the i value for dosomething , it could also be more clear:

limit = len(s) if test else 1
for i in range(limit):
    dosomething()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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