码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-12-14 23:06:43      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:

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

 





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

标签:

原文地址:http://www.cnblogs.com/fengkang1008/p/5046618.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!