Maintaining State in Generators. Python

Introduction

В этой статье продолжается обзор генераторов в Python 3 начатый здесь

Создайте файл generators_demo.py и копируйте туда код из примеров.

Запустить файл можно командой python3 generators_demo.py

Рассмотрим код, который будет возвращать из списка определённое количество неповторяющихся элементов

def take(count, iterable): counter = 0 for item in iterable: if counter == count: return counter += 1 yield item def distinct(iterable): seen = set() for item in iterable: if item in seen: continue yield item seen.add(item) # continue - finish current loop iteration and begin the next iteration immediately def run_pipeline(): items = [3, 6, 6, 2, 1, 1] for item in take(3, distinct(items)): print(item) run_pipeline()

distinct - это генератор, который выдаёт по одному элементу, если этого элемента нет во множестве (в set) seen

take - это тоже генератор - он просто берет определённое количество элементов

python generators_demo.py

3 6 2

Каждый вызов функции-генератора создаёт новый генератор-объект (generator object)

Article author: Andrei Olegovich

Похожие статьи
Interactive mode
str: strings
\: long line wrapping
Lists []
if, elif, else
Loops
Methods
Functions
*args **kwargs
enum
Get Variable Type
Testing with Python
Calling REST API with Python
Files: write, read, append, context manager…
Download File
SQLite3: database
datetime: Date and Time в Python
json.dumps
Selenium + Python
Issues with Python
DJANGO
Flask
ZPL printer script
socket :Python Sockets
Virtual Environment
subprocess: shell commands execution
multiprocessing
psutil: system usage
sys.argv: command prompt variables
PyCharm: IDE
pydantic: data validation
paramiko: SSH with Python
enumerate

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.com
Write to info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: