Python 列表推导、迭代器与生成器

1、列表推导

1
2
3
4
5
6
7
8
9
10
11
numbers = [i for i in range(10) if i % 2 == 0]
print(numbers)
 
seq = ["one", "two", "three"]
for i, element in enumerate(seq):
    print(i, element)
 
def treatment(pos, element):
    return ('%d: %s' % (pos, element))
 
print ([treatment(i, element) for i, element in enumerate(seq)])
1
2
3
4
5
6
enumerate(sequence, [start=0])
 
Return an enumerate object.
sequence must be a sequence, an iterator, or some other object which supports iteration.
The next() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the corresponding value obtained from iterating over iterable.
enumerate() is useful for obtaining an indexed series: (0, seq[0]), (1, seq[1]), (2,seq[2]), ....

2、迭代器

1
2
3
4
5
6
7
8
9
10
11
12
13
class MyIterator(object):
    def __init__(self, step):
        self.step = step
    def __next__(self): # 3.0之后一般采用该样式
        if self.step == 0:
            raise StopIteration
        self.step -= 1
        return self.step
    def __iter__(self):
        return self
 
for i in MyIterator(5):
    print(i)

3、生成器

1
2
3
4
5
6
7
8
9
def fibonacci():
    a, b = 0, 1
    while True:
        yield b
        a, b = b, a + b
fib = fibonacci()
print([next(fib) for i in range(10)]) # >=python 3.0
print(fib.__next__() for i in range(10)]) # >=python 3.0
print(fib.next() for i in range(10)]) # <python 3.0

 





posted @ 2015-12-14 21:34  指上弹兵赵小括  阅读(194)  评论(0编辑  收藏  举报