Python学习笔记二：高级特性 原

leonhu

切片

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']
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)

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)]```

迭代器

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

Python的for循环本质上就是通过不断调用next()函数实现的。

leonhu

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

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

ApacheCN_飞龙
05/18
0
0

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

2015/05/18
2.1K
7

Aikenwu
2018/08/13
0
0

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 应用，让开发更方便。这里...

6
0

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

8
0
Java反射

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

zzz1122334

6
0

go4it

9
0