简体   繁体   中英

How to use python generators with multiple if statements?

say something basic like:

def fizzBuzz(n: int) -> List[str]:
        l =[]
        for i in range(1,n+1):
            if i%3==0 and i%5==0:
                l.append("FizzBuzz")
            elif i%3==0:
                l.append("Fizz")
            elif i%5==0:
                l.append("Buzz")
            else:
                l.append(str(i))
        return l

where input: n=15.
output: [ "1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz", "11", "Fizz", "13", "14", "FizzBuzz" ]
I have started with something like:

["FizzBuzz" if x%3 ==0 and x%5==0 else str(x) for x in range(1, n+1)]

Since you asked for a generator, here is your function converted to one, along with usage.

Notice that fizz_buzz(n) returns a NEW generator, so if you want multiple iterations, you would have to generate a new one every time.

n = 15


def fizz_buzz(n: int):
    for i in range(1, n + 1):
        if i % 3 == 0 and i % 5 == 0:
            yield "FizzBuzz"
        elif i % 3 == 0:
            yield "Fizz"
        elif i % 5 == 0:
            yield "Buzz"
        else:
            yield str(i)


a = fizz_buzz(n)
for f in a:
    print(f)

Output:

 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz

However you may have wanted a list comprehension one liner , and didn't know what it is called and assumed the name was a "generator".

In that case,

b = ["FizzBuzz" if i%3==0 and i%5==0 else "Fizz" if i%3==0 else "Buzz" if i%5==0 else str(i) for i in range(n)]
print(b)

And, this can also be a one-liner-generator :

c = ("FizzBuzz" if i%3==0 and i%5==0 else "Fizz" if i%3==0 else "Buzz" if i%5==0 else str(i) for i in range(n))
for f in c:
    print(f)

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