您的位置:首页 > 编程语言 > Python开发

python 笔记3--高级特性

2015-09-19 09:16 495 查看

切片

语法

L[l:r] 取L[l],L[l+1]…L[r-2],L[r-1]

L[l:r:m] 取L[l],L[l+m],L[l+2*m],L[l+3*m]….(满足l+n*m<=r-1)

tips

字符串,tuple也可以切片

迭代

dict

迭代key

[code]>>> for key in d:
        print(key)


迭代value

[code]for value in d.values()


迭代key和value

[code]for value,key in d.items():
    print(value,key)


字符串

语法

[code]>>> for ch in 'ABC':
...     print(ch)


判断是否属于迭代对象

[code]>>> from collections import Iterable
>>> isinstance('abc', Iterable) # str是否可迭代
True
>>> isinstance([1,2,3], Iterable) # list是否可迭代
True
>>> isinstance(123, Iterable) # 整数是否可迭代
False


调用索引-元素(enumerate)

[code]>>> for i, value in enumerate(['A', 'B', 'C']):
...     print(i, value)
...
0 A
1 B 
2 C


引用两个变量

[code]>>> for x, y in [(1, 1), (2, 4), (3, 9)]:
...     print(x, y)
...
1 1
2 4
3 9


列表生成器

普通list

[code]list(range(1, 11))
或者循环型
[m for m in list(range(1,11))]


多重循环

[code]>>> [m + n for m in 'ABC' for n in 'XYZ']
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']


带判断语句

[code][x * x for x in range(1, 11) if x % 2 == 0]
[4, 16, 36, 64, 100]

//isinstance 判断一个变量是否是某个类型
['Hello', 'World', 18, 'Apple', None]
[s.lower() if isinstance(s,str) else s for s in L]
['hello', 'world', 18, 'apple', None]


生成器

-普通的generator

(x * x for x in range(10))


- 函数 generator

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


原理:

这里,最难理解的就是generator和函数的执行流程不一样。函数是顺序执行,遇到return语句或者最后一行函数语句就返回。而变成generator的函数,在每次调用next()的时候执行,遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行。

捕获return

比较麻烦,暂时不理

小作业

[code]杨辉三角的generator


[code]def triangle(n):
    L=[1]
    while True:
        yield(L)
        L.append(0)
        L=[L[i]+L[i-1] for i in range(len(L))]
        if len(L)>n:
            return "done"

g=triangle(100)
for i in g:
    print(i)


这一句比较奇异,L全部计算完后才赋值给原来的L。

L=[L[i]+L[i-1] for i in range(len(L))]

迭代器

小结

凡是可作用于for循环的对象都是Iterable类型;

是可作用于next()函数的对象都是Iterator类型,它们表示一个惰性计的序列;

集合数据类型如list、dict、str等是Iterable但不是Iterator,不过可以通过iter()函数获得一个Iterator对象。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: