Форум сайта python.su
doza_andМожно обобщить функцию-генератор через интерфейс потока.
Да похоже автору стримов хочется
>>> def g(stream): ... state = 'wait_digit' ... accumulator = '' ... while True: ... ch = stream.read(1) ... if not ch: ... break ... if state == 'wait_digit': ... if ch.isdigit(): ... accumulator += ch ... state = 'wait_nondigit' ... elif state == 'wait_nondigit': ... if ch.isdigit(): ... accumulator += ch ... else: ... number = int(accumulator) ... accumulator = '' ... yield number ... state = 'wait_digit' ... >>> >>> import sys >>> >>> numbers = g(sys.stdin) >>> >>> next(numbers) 111 222 333 x 444 111 >>> next(numbers) 222 >>> next(numbers) 333 >>> next(numbers) 444 >>> next(numbers) 555 555 >>> next(numbers) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration >>> >>> >>> import io >>> >>> numbers = g(io.StringIO(' 11 22 33 x 44 x 55 ')) >>> >>> next(numbers) 11 >>> next(numbers) 22 >>> next(numbers) 33 >>> next(numbers) 44 >>> next(numbers) 55 >>> next(numbers) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration >>>
Отредактировано py.user.next (Июль 30, 2020 09:07:15)
Офлайн