Python3 官方文档翻译 - 5 数据结构
这章会更详细地描述了一些你已经学过的知识,同时添加一些新东西。
5.1 List进阶
下面是关于List的所有方法
>>> a = [66.25, 333, 333, 1, 1234.5]
>>> print(a.count(333), a.count(66.25), a.count('x'))
2 1 0
>>> a.insert(2, -1)
>>> a.append(333)
>>> a
[66.25, 333, -1, 333, 1, 1234.5, 333]
>>> a.index(333)
1
>>> a.remove(333)
>>> a
[66.25, -1, 333, 1, 1234.5, 333]
>>> a.reverse()
>>> a
[333, 1234.5, 1, 333, -1, 66.25]
>>> a.sort()
>>> a
[-1, 1, 66.25, 333, 333, 1234.5]
>>> a.pop()
1234.5
>>> a
[-1, 1, 66.25, 333, 333]
list的用法
你可能会注意到像insert、remove或sort这样的方法只修改了List而没有返回值——其实他们都返回了空值None。这是Python中对所有可变数据结构的一个设计原则
5.1.1 像Stacks那样使用Lists
List的方法让它很容易像Stack那样被使用,最后一个加入的元素第一个被删除("后进先出"原则 )。使用append() 来添加一个元素至栈顶,使用不给定下标的pop() 将一个元素从栈顶移除,示例:
>>> stack = [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
[3, 4, 5, 6, 7]
>>> stack.pop()
7
>>> stack
[3, 4, 5, 6]
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
[3, 4]
5.1.2 像Queues那样使用Lists
>>> from collections import deque
>>> queue = deque(["Eric", "John", "Michael"])
>>> queue.append("Terry") # Terry arrives
>>> queue.append("Graham") # Graham arrives
>>> queue.popleft() # The first to arrive now leaves
'Eric'
>>> queue.popleft() # The second to arrive now leaves
'John'
>>> queue # Remaining queue in order of arrival
deque(['Michael', 'Terry', 'Graham'])
5.1.3 列表生成式
>>> squares = []
>>> for x in range(10):
... squares.append(x**2)
...
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
值得注意的是,我们在loop完成后创建了(甚至可能覆盖)一个名称为 x 的变量。实际上,我们可以通过一行的列表生成式来清晰安全地创建:
squares = list(map(lambda x: x**2, range(10)))
或是等价于:
squares = [x**2 for x in range(10)]
这无疑是更加精确和可读的。
这个列表生成式在圆括号后紧跟了一个for从句,然后是零或多个for 或if 从句,并返回表达式所产生的新list。
例如这个返回结果包含了两个list中互不相等的元素对。
>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
这等价于:
>>> combs = []
>>> for x in [1,2,3]:
... for y in [3,1,4]:
... if x != y:
... combs.append((x, y))
...
>>> combs
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
注意for和if的顺序在这两段代码中是相同的。
就像上例中的(x, y)那样,如果返回结果是一个tuple元组,那么需要在两端加上括号。
>>> vec = [-4, -2, 0, 2, 4]
>>> # create a new list with the values doubled
>>> [x*2 for x in vec]
[-8, -4, 0, 4, 8]
>>> # filter the list to exclude negative numbers
>>> [x for x in vec if x >= 0]
[0, 2, 4]
>>> # apply a function to all the elements
>>> [abs(x) for x in vec]
[4, 2, 0, 2, 4]
>>> # call a method on each element
>>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
>>> [weapon.strip() for weapon in freshfruit]
['banana', 'loganberry', 'passion fruit']
>>> # create a list of 2-tuples like (number, square)
>>> [(x, x**2) for x in range(6)]
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
>>> # the tuple must be parenthesized, otherwise an error is raised
>>> [x, x**2 for x in range(6)]
File "<stdin>", line 1, in ?
[x, x**2 for x in range(6)]
^
SyntaxError: invalid syntax
>>> # flatten a list using a listcomp with two 'for'
>>> vec = [[1,2,3], [4,5,6], [7,8,9]]
>>> [num for elem in vec for num in elem]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
复杂的表达式和嵌套的方法也可以被包含在列表生成式中:
>>> from math import pi
>>> [str(round(pi, i)) for i in range(1, 6)]
['3.1', '3.14', '3.142', '3.1416', '3.14159']
5.1.4 嵌套的列表生成式
>>> matrix = [
... [1, 2, 3, 4],
... [5, 6, 7, 8],
... [9, 10, 11, 12],
... ]
这个列表生成式将会对行和列转置
>>> [[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
使用for来实现内嵌方法,它也可以是这样的:
>>> 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]]
任何的列表生成式都不用 ,它将会是这样的:
>>> 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]]
然而在现实世界中,我们并不希望写出如此复杂的语句。说了那么多,其实使用内置的zip()方法就可以轻松解决:
>>> list(zip(*matrix))
[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
Python3 官方文档翻译 - 5 数据结构的更多相关文章
- Python3 官方文档翻译 - 4.7 函数定义
4.7.1 默认函数定义 最常用的就是为一个或多个参数设定默认值,这让函数可以用比定义时更少的参数来调用,例如: def ask_ok(prompt, retries=4, complaint='Ye ...
- Salt Stack 官方文档翻译 - 一个想做dba的sa - 博客频道 - CSDN.NET
OSNIT_百度百科 Salt Stack 官方文档翻译 - 一个想做dba的sa - 博客频道 - CSDN.NET Salt Stack 官方文档翻译 分类: 自动运维 2013-04-02 11 ...
- Flume官方文档翻译——Flume 1.7.0 User Guide (unreleased version)中一些知识点
Flume官方文档翻译--Flume 1.7.0 User Guide (unreleased version)(一) Flume官方文档翻译--Flume 1.7.0 User Guide (unr ...
- Flume官方文档翻译——Flume 1.7.0 User Guide (unreleased version)(二)
Flume官方文档翻译--Flume 1.7.0 User Guide (unreleased version)(一) Logging raw data(记录原始数据) Logging the raw ...
- 蓝牙4.0——Android BLE开发官方文档翻译
ble4.0开发整理资料_百度文库 http://wenku.baidu.com/link?url=ZYix8_obOT37JUQyFv-t9Y0Sv7SPCIfmc5QwjW-aifxA8WJ4iW ...
- GreenDao官方文档翻译(上)
笔记摘要: 上一篇博客简单介绍了SQLite和GreenDao的比较,后来说要详细介绍下GreenDao的使用,这里就贴出本人自己根据官网的文档进行翻译的文章,这里将所有的文档分成上下两部分翻译,只为 ...
- Aircrack-ng官方文档翻译[中英对照]---Airdecap-ng
Aircrack-ng官方文档翻译---Airdecap-ng Description[简介] With airdecap-ng you can decrypt WEP/WPA/WPA2 capt ...
- Aircrack-ng官方文档翻译[中英对照]---Airmon-ng
Aircrack-ng官方文档翻译---Airmon-ng Description[简介] This script can be used to enable monitor mode on wire ...
- Aircrack-ng官方文档翻译[中英对照]---Aireplay-ng
Aircrack-ng官方文档翻译---Aireplay-ng[90%] Description[简介] Aireplay-ng is used to inject frames. Aireplay- ...
随机推荐
- PendingIntent详解
Intent是一个意图,一个描述了想要启动一个Activity.Broadcast或是Service的意图.它主要持有的信息是它想要启动的组件(Activity.Broadcast或是Service) ...
- 2.Freshman阶段学习内容的确定
我刷知乎.在知乎上答题的程序员,不是很牛逼就是更牛逼,说起各种系统.各种系统的各种版本.各种语言.数据库.算法.IT届的各种圣战都有板有眼.信手拈来.头头是道,不得不服.这导致了一些非常严重的问题:我 ...
- poj2356 Find a multiple(抽屉原理|鸽巢原理)
/* 引用过来的 题意: 给出N个数,问其中是否存在M个数使其满足M个数的和是N的倍数,如果有多组解, 随意输出一组即可.若不存在,输出 0. 题解: 首先必须声明的一点是本题是一定是有解的.原理根据 ...
- 浅谈JSP(一)
一.JSP引言 JSP全名为Java Server Pages,中文名叫java服务器页面,其根本是一个简化的Servlet设计.它是在传统的网页HTML文件(*.htm,*.html)中插入Java ...
- C++变量
一.确保变量的初始化 定义一个变量,int x; 在某些语境下x会初始化为0,但在其他语境下却无法保证. Class CPoint { int m_iX; int m_iY; } CPoint pt; ...
- 1.1. chromium源代码分析 - chromiumframe - 介绍
本人能力有效,面对chromium庞大的代码就头大.还是先由前辈的chromiumFrame入手. 1. chromeFrame概貌 chromiumFrame是前辈的心血之作,以最小化的方式抽出ch ...
- virtualbox 中安装win7虚拟机
下载了win7镜像文件后,在virtualbox中装了几次都提示 windows faied to start,后来在网上找了些解决办法,在这记录下,免得下次又忘了 创建新的虚拟机: 1.安装virt ...
- [LeetCode]题解(python):108-Convert Sorted Array to Binary Search Tree
题目来源: https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/ 题意分析: 给出一个排好序的数组,根据这 ...
- 【双模卡的相关知识】解SIM卡前需要知道的信息(SIM年分和厂商识别)
<ignore_js_op> 二.SIM版本问题SIM卡的版本有两种说法,一是有些是制造厂制定的,二是电信公司的制定.下面以移动为例,目前我们手里的SIM有几种版本:v0.v1.v2.v3 ...
- ActionBarSherlock学习笔记 第一篇——部署
ActionBarSherlock学习笔记 第一篇--部署 ActionBarSherlock是JakeWharton编写的一个开源框架,使用这个框架,可以实现在所有的Android ...