文档章节

Python学习笔记二:高级特性

leonhu
 leonhu
发布于 2017/01/25 05:22
字数 1171
阅读 11
收藏 0

切片

start : end : step

L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
print(L[1:3])
# ['Michael', 'Sarah', 'Tracy']

print(L[:3])
# ['Michael', 'Sarah', 'Tracy']

print(L[-2:-1])

L = list(range(100))

print(L[-10:])
# [90, 91, 92, 93, 94, 95, 96, 97, 98, 99]

print(L[::5])
# [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]

Looping

When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.

for i, v in enumerate(['tic', 'tac', 'toe']):
    print(i, v)

0 tic
1 tac
2 toe

To loop over two or more sequences at the same time, the entries can be paired with the zip() function.

questions = ['name', 'quest','favorite color']

answers = ['lancelot', 'the holy grail', 'yellow']

answers = ['lancelot', 'the holy grail']

for q, a in zip(questions, answers):
    print('What is your {0} ? It is {1}'.format(q,a) )

What is your name ? It is lancelot
What is your quest ? It is the holy grail

To loop over a sequence in reverse, first specify the sequence in a forward direction and then call the reversed() function.

for i in reversed(range(1,10,2)):
    print(i)

9
7
5
3
1

To loop over a sequence in sorted order, use the sorted() function which returns a new sorted list while leaving the source unaltered.

basket = ['banana', 'apple', 'apple']
for f in sorted(set(basket)):
    print(f)

apple
banana

It is sometimes tempting to change a list while you are looping over it; however, it is often simpler and safer to create a new list instead.

import math
raw_data = [63.22, float('NaN')]
print(raw_data)
filtered_data = []
for v in raw_data:
    if not math.isnan(v):
        filtered_data.append(v)

print(filtered_data)

[63.22, nan]
[63.22]

List Comprehensions

List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.

squares = [x**2 for x in range(1,11) if x%2==0]
print(squares)

[4, 16, 36, 64, 100]

A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it. For example, this listcomp combines the elements of two lists if they are not equal:

data = [(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x!=y]
print(data)

[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

new words:

List Comprehensions 列表推导
parenthesized 括号
snippets 片段
brackets  括弧

For example, we can list all files and dir name of current directory by one line of code:

import  os
dir = [d for d in os.listdir('.')]
print(dir)
# ['.idea', 'Intro_1.py', 'Python_advanced_features.py', 'Test.py']

Practice:

L consists of string and non-string, build a new list in which each element is string and lower case.

L = ['Hello', 'World', 18, 'Apple', None]
L_str = [s.lower() for s in L if isinstance(s,str)]
print(L_str)

['hello', 'world', 'apple']

Nested List Comprehensions

嵌套列表解析

Consider the following example of a 3x4 matrix implemented as a list of 3 lists of length 4:

>>>

matrix = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
]

The following list comprehension will transpose rows and columns:

>>> [[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

As we saw in the previous section, the nested listcomp is evaluated in the context of the for that follows it, so this example is equivalent to:

>>> transposed = []
>>> for i in range(4):
...     transposed.append([row[i] for row in matrix])
...
>>> transposed
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

which, in turn, is the same as:

>>> transposed = []
>>> for i in range(4):
...     # the following 3 lines implement the nested listcomp
...     transposed_row = []
...     for row in matrix:
...         transposed_row.append(row[i])
...     transposed.append(transposed_row)
...
>>> transposed
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

In the real world, you should prefer built-in functions to complex flow statements. The zip() function would do a great job for this use case:

 

>>> list(zip(*matrix))
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]

迭代器

我们已经知道,可以直接作用于for循环的数据类型有以下几种:
一类是集合数据类型,如list、tuple、dict、set、str等;
一类是generator,包括生成器和带yield的generator function。
这些可以直接作用于for循环的对象统称为可迭代对象:Iterable。
可以使用isinstance()判断一个对象是否是Iterable对象:

>>> 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

而生成器不但可以作用于for循环,还可以被next()函数不断调用并返回下一个值,直到最后抛出StopIteration错误表示无法继续返回下一个值了。
可以被next()函数调用并不断返回下一个值的对象称为迭代器:Iterator。
可以使用isinstance()判断一个对象是否是Iterator对象:

>>> from collections import Iterator
>>> isinstance((x for x in range(10)), Iterator)
True
>>> isinstance([], Iterator)
False
>>> isinstance({}, Iterator)
False
>>> isinstance('abc', Iterator)
False

生成器都是Iterator对象,但list、dict、str虽然是Iterable,却不是Iterator。
把list、dict、str等Iterable变成Iterator可以使用iter()函数:

>>> isinstance(iter([]), Iterator)
True
>>> isinstance(iter('abc'), Iterator)
True

小结

凡是可作用于for循环的对象都是Iterable类型;
凡是可作用于next()函数的对象都是Iterator类型,它们表示一个惰性计算的序列;
集合数据类型如list、dict、str等是Iterable但不是Iterator,不过可以通过iter()函数获得一个Iterator对象。
Python的for循环本质上就是通过不断调用next()函数实现的。

 

 

© 著作权归作者所有

leonhu
粉丝 0
博文 38
码字总数 13436
作品 0
深圳
私信 提问
分享我自己写的一套Python爬虫学习经验

最近在学习Python爬虫,感觉非常有意思,真的让生活可以方便很多。学习过程中我把一些学习的笔记总结下来,还记录了一些自己实际写的一些小爬虫,在这里跟大家一同分享,希望对Python爬虫感兴...

崔庆才
2015/02/23
4K
25
ApacheCN 人工智能知识树 v1.0

Special Sponsors 贡献者:飞龙 版本:v1.0 最近总是有人问我,把 ApacheCN 这些资料看完一遍要用多长时间,如果你一本书一本书看的话,的确要用很长时间。但我觉得这是非常麻烦的,因为每本...

ApacheCN_飞龙
05/18
0
0
编程语言太难学?只因你还没试过Python!

Python语言可能是第一种即简单又功能强大的编程语言。它不仅适合于初学者,也适合于专业人员使用,更加重要的是,用Python编程是一种愉快的事。本身将帮助你学习这个奇妙的语言,并且向你展示...

极客学院
2015/05/18
2.1K
7
基于编程人员Python学习第一章节

基于廖雪峰的python零基础学习后,自我总结。适用于有一定基础的编程人员,对我而言,则是基于.net已有方面,通过学习,记录自我觉得有用的地方,便于后续回顾。 主要以快速定位内容,通过直...

Aikenwu
2018/08/13
0
0
利用python函数的输入、输出定义与时序图相结合,让生活更有趣

写在前面 1. 重点是思路交流,利用python函数的输入、输出定义与时序图相结合,让流程更加的简洁、清晰。该方法不局限于工作,同样适用于学习笔记、恋爱心得...等等只要存在个体交互的活动。...

python达人
2018/05/08
0
0

没有更多内容

加载失败,请刷新页面

加载更多

golang-字符串-地址分析

demo package mainimport "fmt"func main() {str := "map.baidu.com"fmt.Println(&str, str)str = str[0:5]fmt.Println(&str, str)str = "abc"fmt.Println(&s......

李琼涛
今天
4
0
Spring Boot WebFlux 增删改查完整实战 demo

03:WebFlux Web CRUD 实践 前言 上一篇基于功能性端点去创建一个简单服务,实现了 Hello 。这一篇用 Spring Boot WebFlux 的注解控制层技术创建一个 CRUD WebFlux 应用,让开发更方便。这里...

泥瓦匠BYSocket
今天
6
0
从0开始学FreeRTOS-(列表与列表项)-3

FreeRTOS列表&列表项的源码解读 第一次看列表与列表项的时候,感觉很像是链表,虽然我自己的链表也不太会,但是就是感觉很像。 在FreeRTOS中,列表与列表项使用得非常多,是FreeRTOS的一个数...

杰杰1号
今天
8
0
Java反射

Java 反射 反射是框架设计的灵魂(使用的前提条件:必须先得到代表的字节码的 Class,Class 类 用于表示.class 文件(字节码)) 一、反射的概述 定义:JAVA 反射机制是在运行状态中,对于任...

zzz1122334
今天
6
0
聊聊nacos的LocalConfigInfoProcessor

序 本文主要研究一下nacos的LocalConfigInfoProcessor LocalConfigInfoProcessor nacos-1.1.3/client/src/main/java/com/alibaba/nacos/client/config/impl/LocalConfigInfoProcessor.java p......

go4it
昨天
9
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部