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

python入门(三)

时间:2018-01-15 00:20:50      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:print   deb   技术   调用   有一个   traceback   filter   value   recent   

Slice(切片)

技术分享图片
>>> L = [Michael, Sarah, Tracy, Bob, Jack]
>>> L[0:3]
[Michael, Sarah, Tracy]
>>> L[:3]
[Michael, Sarah, Tracy]
>>> L[1:3]
[Sarah, Tracy]


>>> L[-2:]
[Bob, Jack]
>>> L[-2:-1]
[Bob]

>>> L = list(range(100))
>>> L
[0, 1, 2, 3, ..., 99]
>>> L[:]
[0, 1, 2, 3, ..., 99]
>>> L[:10:2]
[0, 2, 4, 6, 8]
>>> L[::5]
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
View Code
技术分享图片
>>> (0, 1, 2, 3, 4, 5)[:3]
(0, 1, 2)
View Code
技术分享图片
>>> ABCDEFG[:3]
ABC
>>> ABCDEFG[::2]
ACEG
View Code

For ... in ...(迭代)

默认情况下,dict迭代的是key。如果要迭代value,可以用for value in d.values(),如果要同时迭代key和value,可以用for k, v in d.items()。

技术分享图片
>>> d = {a: 1, b: 2, c: 3}
>>> for key in d:
...     print(key)
...
a
c
b
View Code
技术分享图片
>>> for ch in ABC:
...     print(ch)
...
A
B
C
View Code

 判断可迭代对象

技术分享图片
>>> from collections import Iterable
>>> isinstance(abc, Iterable) # str是否可迭代
True
>>> isinstance([1,2,3], Iterable) # list是否可迭代
True
>>> isinstance(123, Iterable) # 整数是否可迭代
False
View Code
技术分享图片
>>> for i, value in enumerate([A, B, C]):
...     print(i, value)
...
0 A
1 B
2 C
View Code
技术分享图片
>>> for x, y in [(1, 1), (2, 4), (3, 9)]:
...     print(x, y)
...
1 1
2 4
3 9
View Code

列表生成式

技术分享图片
>>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

>>> [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]
[4, 16, 36, 64, 100]

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

>>> d = {x: A, y: B, z: C }
>>> [k + = + v for k, v in d.items()]
[y=B, x=A, z=C]

>>> L = [Hello, World, IBM, Apple]
>>> [s.lower() for s in L]
[hello, world, ibm, apple]
View Code

 生成器

技术分享图片
>>> g = (x * x for x in range(10))
>>> g
<generator object <genexpr> at 0x1022ef630>
View Code
技术分享图片
>>> next(g)
0
>>> next(g)
1
>>> next(g)
4
>>> next(g)
9
>>> next(g)
16
>>> next(g)
25
>>> next(g)
36
>>> next(g)
49
>>> next(g)
64
>>> next(g)
81
>>> next(g)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
View Code

generator保存的是算法,每次调用next(g),就计算出g的下一个元素的值,直到计算到最后一个元素,没有更多的元素时,抛出StopIteration的错误。

技术分享图片
>>> g = (x * x for x in range(10))
>>> for n in g:
...     print(n)
... 
0
1
4
9
16
25
36
49
64
81
View Code

如果一个函数定义中包含yield关键字,那么这个函数就不再是一个普通函数,而是一个generator。generator的函数,在每次调用next()的时候执行,遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行。

技术分享图片
def odd():
    print(step 1)
    yield 1
    print(step 2)
    yield(3)
    print(step 3)
    yield(5)


>>> o = odd()
>>> next(o)
step 1
1
>>> next(o)
step 2
3
>>> next(o)
step 3
5
>>> next(o)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
View Code

 map

技术分享图片
>>> def f(x):
...     return x * x
...
>>> r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> list(r)
[1, 4, 9, 16, 25, 36, 49, 64, 81]
View Code

reduce

技术分享图片
>>> from functools import reduce
>>> def add(x, y):
...     return x + y
...
>>> reduce(add, [1, 3, 5, 7, 9])
25
View Code
技术分享图片
>>> from functools import reduce
>>> def fn(x, y):
...     return x * 10 + y
...
>>> reduce(fn, [1, 3, 5, 7, 9])
13579
View Code

filter

技术分享图片
def is_odd(n):
    return n % 2 == 1

list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
# 结果: [1, 5, 9, 15]
View Code
技术分享图片
def not_empty(s):
    return s and s.strip()

list(filter(not_empty, [A, ‘‘, B, None, C,   ]))
# 结果: [‘A‘, ‘B‘, ‘C‘]
View Code

sorted

技术分享图片
>>> sorted([36, 5, -12, 9, -21])
[-21, -12, 5, 9, 36]
View Code
技术分享图片
>>> sorted([36, 5, -12, 9, -21], key=abs)
[5, 9, -12, -21, 36]
View Code
技术分享图片
>>> sorted([bob, about, Zoo, Credit])
[Credit, Zoo, about, bob]
View Code
技术分享图片
>>> sorted([bob, about, Zoo, Credit], key=str.lower)
[about, bob, Credit, Zoo]
View Code
技术分享图片
L = [(Bob, 75), (Adam, 92), (Bart, 66), (Lisa, 88)]
list(sorted(L,key=lambda x :x[1]))
View Code

 闭包

技术分享图片
def count():
    fs = []
    for i in range(1, 4):
        def f():
             return i*i
        fs.append(f)
    return fs

f1, f2, f3 = count()

>>> f1()
9
>>> f2()
9
>>> f3()
9
View Code
技术分享图片
def count():
    def f(j):
        def g():
            return j*j
        return g
    fs = []
    for i in range(1, 4):
        fs.append(f(i)) # f(i)立刻被执行,因此i的当前值被传入f()
    return fs


>>> f1, f2, f3 = count()
>>> f1()
1
>>> f2()
4
>>> f3()
9
View Code

匿名函数 lambda

只能有一个表达式,不用写return,返回值就是该表达式的结果。

技术分享图片
>>> f = lambda x: x * x
>>> f
<function <lambda> at 0x101c6ef28>
>>> f(5)
25


def build(x, y):
    return lambda: x * x + y * y
View Code

装饰器

代码运行期间动态增加功能的方式,称之为“装饰器”(Decorator)。

偏函数

技术分享图片
>>> import functools
>>> int2 = functools.partial(int, base=2)
>>> int2(1000000)
64
>>> int2(1010101)
85


>>> int2(1000000, base=10)
1000000
View Code

no yuchuang.just shuxishuxi.

python入门(三)

标签:print   deb   技术   调用   有一个   traceback   filter   value   recent   

原文地址:https://www.cnblogs.com/Merrys/p/8283142.html

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