Домой Edit me on GitHub

2020-12-05

Каналы передачи данных | Сетевое программирование | Базы данных | Основы Веб-программирования

Генераторы

Python

См.также

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def id_maker():
    index = 0
    while True:
        yield index
        index += 1

gen = id_maker()

print(next(gen))
print(next(gen))
print(next(gen))

Запуск:

$ python gen.py
0
1
2
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class CSVFile(object):
    def __init__(self, path, sep=','):
        self.path = path
        self.sep = sep

    def __iter__(self):
        with open(self.path) as f:
            for l in f:
                yield l.split(self.sep)

csv_generator = CSVFile('sample.csv')

for row in csv_generator:
    print(row)
1
2
3
1997,Ford,E350,"ac, abs, moon",3000.00
1999,Chevy,"Venture ""Extended Edition""","",4900.00
1996,Jeep,Grand Cherokee,"MUST SELL! air, moon roof, loaded",4799.00
$ python csv_gen.py
['1997', 'Ford', 'E350', '"ac', ' abs', ' moon"', '3000.00\n']
['1999', 'Chevy', '"Venture ""Extended Edition"""', '""', '4900.00\n']
['1996', 'Jeep', 'Grand Cherokee', '"MUST SELL! air', ' moon roof', ' loaded"', '4799.00\n']

JavaScript

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
function* idMaker(){
    var index = 0;
    while(true)
        yield index++;
}

var gen = idMaker();

console.log(gen.next().value); // 0
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2

Запуск:

$ iojs gen.js
0
1
2
Previous: Декораторы для корутин в asyncio Next: Текстовые редакторы