如何编写一行Python生成器表达式生成1-99的无限奇数流及奇随机数流?
Got you covered! Let's break down the two generator expressions you need step by step:
1. Infinite Cycling Stream of Odd Numbers (1 to 99)
This generator will loop through all odd numbers from 1 to 99 repeatedly, creating an infinite stream:
import itertools odd_cycle = (num for num in itertools.cycle(range(1, 100, 2)))
Here's how it works:
range(1, 100, 2)generates all odd numbers from 1 to 99 (we start at 1 and step by 2 to skip even numbers)itertools.cycle()takes that fixed sequence of odds and repeats it infinitely- The generator expression wraps this cycled sequence to spit out values one at a time on demand
2. Infinite Stream of Random Odd Numbers (1 to 99)
For a stream of random odd numbers within the 1-99 range, we'll pair the random module with an infinite counter to keep generating values:
import random import itertools random_odds = (random.randrange(1, 100, 2) for _ in itertools.count())
If you prefer working with a pre-defined list of odds (useful if you need to reuse the sequence elsewhere), you can also use random.choice():
odd_numbers = range(1, 100, 2) random_odds = (random.choice(odd_numbers) for _ in itertools.count())
How this works:
itertools.count()generates an endless sequence of integers (0, 1, 2, ...) which acts as our "infinite loop trigger"random.randrange(1, 100, 2)directly picks a random odd number from the range each iterationrandom.choice(odd_numbers)selects a random element from the pre-made odd sequence
A quick note: when testing these generators, always add a break condition to your loop—otherwise it'll run forever! For example:
# Test the cycling stream for idx, num in enumerate(odd_cycle): print(num) if idx == 20: # Stop after 21 values break # Test the random stream for idx, num in enumerate(random_odds): print(num) if idx == 10: # Stop after 11 values break
内容的提问来源于stack exchange,提问作者user3499084
相关产品推荐
相关产品推荐

