Python3基础-高级用法

Posted 既生喻何生亮(Bright)

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python3基础-高级用法相关的知识,希望对你有一定的参考价值。

写在前面:本文主要是python高级练习部分,介绍了一些高级用法,这些都是零散的小知识,这些可以与函数式编程合在一起使用。

函数式编程[1]:Python中提供的函数式编程主要有:

  • map(函数,可迭代式)映射函数
  • filter(函数,可迭代式)过滤函数
  • reduce(函数,可迭代式)规约函数
  • lambda函数
  • 列表推导式
  • zip()函数

generator 生成

词汇

generator 英[ˈdʒenəreɪtə(r)] 美[ˈdʒɛnəˌretɚ]

n. 发电机,发生器; 电力公司; 生产者,创始者; [乐] 基础低音

My understanding

关于生成器的基本概念,我没有详述,因为有关它的描述,网上一搜,一大把,在我看来,学习最有效的方法就是自己运行案例,通过案例反映生成器的作用。

比如,【点这里】,哈哈这也是总结的。

案例1:元组推导式自动生成 generator

s = (x * x for x in range(5))
print(s)
<generator object <genexpr> at 0x000001343C239F10>
for x in s:
    print(x, end=\',\')
0,1,4,9,16,

案例2:Fibonacci sequence

【原理,点我】

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

f = fib(10)
print(\'fib(10)\', f)
fib(10) <generator object fib at 0x000001343C239E08>
for x in f:
    print(x, end=\' \')
1 1 2 3 5 8 13 21 34 55 
g = fib(5)
while 1:
    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
Generator return value: done

iter 迭代

其实,迭代有可迭代的迭代器,一个是形容词,一个是名词,所以他们是与区别的。

如果要使用需要导入from collections import Iterable, Iterator

案例1:可迭代的

from collections import Iterable, Iterator

def g():
    yield 1
    yield 2
    yield 3
    
print(\'Iterable? [1, 2, 3]:\', isinstance([1, 2, 3], Iterable))
print(\'Iterable? \\\'abc\\\':\', isinstance(\'abc\', Iterable))
print(\'Iterable? 123:\', isinstance(123, Iterable))
print(\'Iterable? g():\', isinstance(g(), Iterable))
Iterable? [1, 2, 3]: True
Iterable? \'abc\': True
Iterable? 123: False
Iterable? g(): True

综上:

  1. 列表是可迭代的
  2. 字符串是可迭代的
  3. 数字是不可迭代的的
  4. 自定义的g()函数是可迭代的

案例2:迭代器

如果我们使用iter()函数作用,可将列表and元组转化为迭代器。

print(\'Iterator? [1, 2, 3]:\', isinstance([1, 2, 3], Iterator))
print(\'Iterator? iter([1, 2, 3]):\', isinstance(iter([1, 2, 3]), Iterator))
print(\'Iterator? \\\'abc\\\':\', isinstance(\'abc\', Iterator))
print(\'Iterator? 123:\', isinstance(123, Iterator))
print(\'Iterator? g():\', isinstance(g(), Iterator))
print(\'Iterator? (1, 2, 3):\', isinstance((1, 2, 3), Iterator))
print(\'Iterator? iter((1, 2, 3)):\', isinstance(iter((1, 2, 3)), Iterator))
Iterator? [1, 2, 3]: False
Iterator? iter([1, 2, 3]): True
Iterator? \'abc\': False
Iterator? 123: False
Iterator? g(): True
Iterator? (1, 2, 3): False
Iterator? iter((1, 2, 3)): True

综上:

  1. 列表 not is 迭代器
  2. 采用iter()转化的列表 is 迭代器
  3. 字符串not is 迭代器
  4. 数字not is 迭代器
  5. 自定义的g()函数is 迭代器
  6. 元组 not is 迭代器
  7. 采用iter()转化的元组 is 迭代器

案例3:迭代元素

例子1

print(\'for x in [1, 2, 3, 4, 5]:\')
for x in [1, 2, 3, 4, 5]:
    print(x)
for x in [1, 2, 3, 4, 5]:
1
2
3
4
5

例子2

print(\'for x in iter([1, 2, 3, 4, 5]):\')
for x in iter([1, 2, 3, 4, 5]):
    print(x)
for x in iter([1, 2, 3, 4, 5]):
1
2
3
4
5

例子3

print(\'next():\')
it = iter([1, 2, 3, 4, 5])
print(next(it))
print(next(it))
print(next(it))
print(next(it))
print(next(it))
next():
1
2
3
4
5

案例4:字典迭代

想知道,字典的情况【点我】

构造字典

key = \'a\', \'b\', \'c\'
value = 1, 2, 3
d = dict(zip(key, value))

迭代字典的键

print(\'iter key:\', d)
for k in d.keys():
    print(\'key:\', k)
iter key: {\'a\': 1, \'b\': 2, \'c\': 3}
key: a
key: b
key: c

迭代字典的值

print(\'iter value:\', d)
for v in d.values():
    print(\'value:\', v)
iter value: {\'a\': 1, \'b\': 2, \'c\': 3}
value: 1
value: 2
value: 3

迭代字典的键值对

print(\'iter item:\', d)
for k, v in d.items():
    print(\'item:\', k, v)
iter item: {\'a\': 1, \'b\': 2, \'c\': 3}
item: a 1
item: b 2
item: c 3

列表迭代与推导

列表操作原理,【点我】

列表迭代

for i, value in enumerate([\'A\', \'B\', \'C\']):
    print(i, value)
0 A
1 B
2 C
for x, y in [(1, 1), (2, 4), (3, 9)]:
    print(x, y)
1 1
2 4
3 9

列表推导式

print([x*x for x in range(1, 11)])
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
print([x*x for x in range(1, 11) if x%2 == 0])
[4, 16, 36, 64, 100]
print([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\'}
print([k + \'=\' + v for k, v in d.items()])
[\'x=A\', \'y=B\', \'z=C\']
L = [\'Hello\', \'World\', \'Apple\', \'IBM\']
print([s.lower() for s in L])
[\'hello\', \'world\', \'apple\', \'ibm\']

切片

L = [\'Michael\', \'Sarah\', \'Tracy\', \'Bob\', \'Jack\']
for i, value in enumerate(L):
    print("L列表中元素的序:{}-->{}-->{}".format(i, value, i-len(L)))
L列表中元素的序:0-->Michael-->-5
L列表中元素的序:1-->Sarah-->-4
L列表中元素的序:2-->Tracy-->-3
L列表中元素的序:3-->Bob-->-2
L列表中元素的序:4-->Jack-->-1
print(\'L[0:3] =\', L[0:3])
print(\'L[:3] =\', L[:3])
print(\'L[1:3] =\', L[1:3])
print(\'L[-2:] =\', L[-2:])
L[0:3] = [\'Michael\', \'Sarah\', \'Tracy\']
L[:3] = [\'Michael\', \'Sarah\', \'Tracy\']
L[1:3] = [\'Sarah\', \'Tracy\']
L[-2:] = [\'Bob\', \'Jack\']
R = list(range(100))
print(\'R[:10] =\', R[:10])
print(\'R[-10:] =\', R[-10:])
print(\'R[10:20] =\', R[10:20])
print(\'R[:10:2] =\', R[:10:2])
print(\'R[::5] =\', R[::5])
R[:10] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
R[-10:] = [90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
R[10:20] = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
R[:10:2] = [0, 2, 4, 6, 8]
R[::5] = [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]

关于yeild的例子

完整的代码

def each_ascii(s):
    for ch in s:
        yield ord(ch)
    return \'%s chars\' % len(s)

def yield_from(s):
    r = yield from each_ascii(s)
    print(r)

def main():
    for x in each_ascii(\'abc\'):
        print(x) # => \'a\', \'b\', \'c\'
    it = each_ascii(\'xyz\')
    try:
        while True:
            print(next(it)) # => \'x\', \'y\', \'z\'
    except StopIteration as s:
        print(s.value) # => \'3 chars\'

    # using yield from in main() will change main() from function to generator:
    # r = yield from each_ascii(\'hello\')

    for ch in yield_from(\'hello\'):
        pass

main()

代码分析

def each_ascii(s):
    for ch in s:
        yield ord(ch)
    return \'%s chars\' % len(s)
def yield_from(s):
    r = yield from each_ascii(s)
    print(r)
for x in each_ascii(\'abc\'):
    print(x)
97
98
99
it = each_ascii(\'xyz\')
try:
    while True:
        print(next(it))
except StopIteration as s:
    print(s.value)
120
121
122
3 chars
for ch in yield_from(\'hello\'):
    pass
5 chars

总结

有时候,对编程不感冒,但是把一个复杂的知识点多运行几遍,太复杂了,把代码分成小代码运行,最后综合理解,并整理成文。当然,这涉及到调试代码部分,现在我还是个小菜鸟,调试用的不太熟,当然代码量很大的时候可能要用到调试部分。

End


  1. 我总结的一些笔记 ↩︎

以上是关于Python3基础-高级用法的主要内容,如果未能解决你的问题,请参考以下文章

Python3网络爬虫实战-25requests:高级用法

python3 f-string格式化字符串的高级用法

Python3.6:bs4解析html基础用法

Python3高级基础

Python3基础语句/符号用法规则

#yyds干货盘点#return用法 - python基础学习系列(64)