# 关于python的一些高级特性

>>> [x * x for x in range(1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

>>> [x * x for x in range(1, 11) if x%2==0]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

>>> [m + n for m in ‘abc’ for n in ‘xyz’]
[‘ax’, ‘ay’, ‘az’, ‘bx’, ‘by’, ‘bz’, ‘cx’, ‘cy’, ‘cz’]

>>> [m + n for m in ‘abc’ if m < 'c' for n in 'xyz' if n < 'z'] ['ax', 'ay', 'bx', 'by'] >>> [m + n for m in ‘abc’ for n in ‘xyz’ if n < 'z' and m < 'c'] ['ax', 'ay', 'bx', 'by']

>>> d = {‘x’: ‘a’, ‘y’: ‘b’, ‘z’: ‘c’ }
>>> [k + ‘=’ + v for k, v in d.items()]
[‘y=b’, ‘x=a’, ‘z=c’]

>>> l = [x * x for x in range(10)]
>>> l
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> g = (x * x for x in range(10))
>>> g

>>> for i in g:
… print(i)

0
1
4
9
16
25
36
49
64
81
>>> for i in g:
… print(i)

>>> next(g)
traceback (most recent call last):
file “”, line 1, in
stopiteration

def fib(max):
n, a, b = 0, 0, 1
while n < max: yield b a, b = b, a + b n = n + 1 return 'done'

>>> g = fib(6)
>>> while true:
… try:
… x = next(g)
… print(‘g:’, x)
… except stopiteration as e:
… print(‘generator return value:’, e.value)
… break

g: 1
g: 1
g: 2
g: 3
g: 5
g: 8
generator return value: done迭代器(iterator)

>>> from collections import iterable
>>> isinstance([], iterable)
true
>>> isinstance({}, iterable)
true
>>> isinstance(‘abc’, iterable)
true
>>> isinstance((x for x in range(10)), iterable)
true
>>> isinstance(100, iterable)
false

>>> from collections import iterator
>>> isinstance((x for x in range(10)), iterator)
true
>>> isinstance([], iterator)
false
>>> isinstance({}, iterator)
false
>>> isinstance(‘abc’, iterator)
false

>>> isinstance(iter([]), iterator)
true
>>> isinstance(iter(‘abc’), iterator)
true

Posted in 未分类