数据结构(Data Structures)
一、List数据类型的方法
定义两个list,a和b:a=[1,2,3,4],b=[7,8,9,10]
a.append(x) 在a的末尾附加x元素
a.extend(b) 在a的末尾添加b的所有元素
a.insert(i,x) 在a的第i个元素位置之后插入x元素,即a.insert(len(a),x)等价于a.append(x)
a.remove(x) 在a中移除第一个出现的x元素
a.pop() 返回:a的最后一个元素,并在a中删除该元素
a.index(x) 返回x元素的索引值,若a中不存在x元素,则返回一个错误
a.count(x) 返回x元素在a中出现的次数
a.sort() 对a中的元素进行排序
a.reverse() 将a中的元素逆序
del a[i] 删除该元素
(以上这些方法都是在原来的表的上进行操作,会对原来的表产生影响,而不是返回一个新表。)
>>> a=[,,,]
>>> a.append()
>>> a
[, , , , ]
>>> a.insert(,)
>>> a
[, , , , , ]
>>> b=[,,,]
>>> a.extend(b)
>>> a
[, , , , , , , , , ]
>>> a.remove()
>>> a
[, , , , , , , , ]
>>> a.pop() >>> a
[, , , , , , , ]
>>> a.index() >>> a.count() >>> a.reverse()
>>> a
[, , , , , , , ]
>>> del a[]
>>> a
[, , , , , , ]
>>> a.sort()
>>> a
[, , , , , , ]
二、List作为stacks使用
Stack:堆栈,即后进先出(last-in, first-out),只有一端(称为栈顶(top))对数据项进行插入和移除,在栈顶使用append()添加一个元素,在栈顶使用pop()移除一个元素。
>>> stack=[1,2,3]
>>> stack.append(4)
>>> stack.append(5)
>>> stack
[1, 2, 3, 4, 5]
>>> stack.pop()
5
>>> stack
[1, 2, 3, 4]
>>> stack.pop()
4
>>> stack.pop()
3
>>> stack
[1, 2]
三、List作为queues使用
Queue:队列,即先进先出(first-in, first-out),一头进一头出,先进去的在前面,自然先从另一边出来。
注意:此处list作为queue使用,效率不是很高,当往list的结尾处添加(append())或移除(pop())元素时是快的,当往list的开始处插入(insert())或移除(pop())元素时是慢的,原因是后者所有的其它元素都需要移动。这里建议使用collections.deque,它在前后两端appends和pops时都很快。
>>> from collections import deque
>>> queue = deque(["Eric","John","Michael"])
>>> queue.append("Terry")
>>> queue.append("Graham")
>>> queue.popleft()
'Eric'
>>> queue.popleft()
'John'
>>> queue
deque(['Michael', 'Terry', 'Graham'])
四、filter()、map()、reduce()方法使用
filter(function,sequence):对sequence中的item依次执行function(item),将执行结果为True的item组成一个list/string/tuple(取决于sequence的类型)返回:
>>> def f(x):return x % 3 == 0 or x % 5 == 0
>>> filter(f,range(2,25))
[3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24]
>>> def f(x):return x != 'a'
>>> filter(f,"abcdef")
'bcdef'
map(function,sequence):对sequence中的item依次执行function(item),将执行结果组成一个list返回:
>>> def cube(x):return x*x*x
>>> map(cube,range(1,11))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
>>> def cube(x):return x+x
>>> map(cube,"abcde")
['aa', 'bb', 'cc', 'dd', 'ee']
>>> def add(x,y):return x+y
>>> map(add,range(8),range(8))
[0, 2, 4, 6, 8, 10, 12, 14]
reduce(function,sequence):对sequence中的item顺序迭代调用function,如果有starting_value,还可以作为初始值调用,例如可以用来对list求和:
>>> def add(x,y):return x+y
>>> reduce(add,range(1,11))
55 (注:1+2+3+4+5+6+7+8+9+10)
>>> def add(x,y):return x+y
>>> reduce(add,range(1,11),20)
75 (注:1+2+3+4+5+6+7+8+9+10+20)
五、List Comprehensions
列表推导式(list comprehension)是一种方便简介的语法形式,我们可以利用它将一个list经过过滤后转换成另一个list,也可以利用它将函数应用于list中的元素。
>>> squares = [x**2 for x in range(10)]
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
squares = [x**2 for x in range(10)] 等价于以下常规写法
>>> squares = []
>>> for x in range(10):
... squares.append(x**2)
...
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
是不是上面看起来更简洁及可读性更好,再举一例如下:
>>> [(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)]
具体应用如下:
>>> vec = [-4,-2,0,2,4]
>>> [x*2 for x in vec] #返回一个新的list,新list元素值是原先元素值的2倍
[-8, -4, 0, 4, 8]
>>> [x for x in vec if x>=0] #返回一个新的list,值为原list中大于0的元素
[0, 2, 4]
>>> [abs(x) for x in vec] #返回一个新的list,值为对原list中的元素值求绝对值
[4, 2, 0, 2, 4] >>> freshfruit = [' banana',' apple','orange ']
>>> [weapon.strip() for weapon in freshfruit] #strip()去掉前后空格
['banana', 'apple', 'orange']
>>> [(x,x**2) for x in range(6)]
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
>>> 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]
List comprehensions支持复杂的表达式和嵌套函数
>>> from math import pi
>>> [str(round(pi,i)) for i in range(1,6)]
['3.1', '3.14', '3.142', '3.1416', '3.14159'] >>> 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]]
六、Tuples和Sequences
sequence(序列)是一组有顺序的元素的集合
(严格的说,是对象的集合,但鉴于我们还没有引入“对象”概念,暂时说元素)
序列可以包含一个或多个元素,也可以没有任何元素。
我们之前所说的基本数据类型,都可以作为序列的元素。元素还可以是另一个序列,以及我们以后要介绍的其他对象。
序列有两种:tuple(定值表; 也有翻译为元组) 和 list (表)
序列有两种:tuple(定值表; 也有翻译为元组) 和 list (表)
>>>s1 = (2, 1.3, 'love', 5.6, 9, 12, False) # s1是一个tuple
>>>s2 = [True, 5, 'smile'] # s2是一个list
tuple和list的主要区别在于,一旦建立,tuple的各个元素不可再变更,而list的各个元素可以再变更。
七、Sets
Set:创建一个无序不重复的元素集,基本功能包含关系测试和消除重复元素,集合对象还支持union(联合),intersection(交),difference(差)和sysmmetric difference(对称差集)等数学运算。
>>> basket = ['apple','orange','apple','pear','orange','banana']
>>> fruit = set(basket)
>>> fruit
set(['orange', 'pear', 'apple', 'banana'])
>>> 'orange' in fruit
True
>>> 'crabgrass' in fruit
False >>> a = set('abracadabra')
>>> b =set('alacazam')
>>> a
set(['a', 'r', 'b', 'c', 'd'])
>>> b
set(['a', 'c', 'z', 'm', 'l'])
>>> a-b
set(['r', 'b', 'd'])
>>> a|b
set(['a', 'c', 'b', 'd', 'm', 'l', 'r', 'z'])
>>> a&b
set(['a', 'c'])
>>> a^b
set(['b', 'd', 'm', 'l', 'r', 'z']) >>> a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
set(['r', 'd'])
八、字典(Dictionaries)
字典:存储一对key、value
>>> tel={'jack':4098,'sape':4139}
>>> tel['guido'] = 4127
>>> tel
{'sape': 4139, 'jack': 4098, 'guido': 4127}
>>> tel['jack']
4098
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'jack': 4098, 'irv': 4127, 'guido': 4127}
>>> tel.keys()
['jack', 'irv', 'guido']
>>> 'guido' in tel
True >>> dict([('sape',4139),('guido',4127),('jack',4098)])
{'sape': 4139, 'jack': 4098, 'guido': 4127}
>>> dict(sape=4139,guido=4127,jack=4098)
{'sape': 4139, 'jack': 4098, 'guido': 4127}
dict()构造方法可以从一个key-value序列创建成字典
九、循环技巧
>>> for i,v in enumerate(['tic','tac','toe']):
... print i,v
...
0 tic
1 tac
2 toe
>>> questions = ['name','quest','favorite color']
>>> answers = ['lancelot','the holy grail','blue']
>>> 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.
What is your favorite color? It is blue. >>> for i in reversed(xrange(1,10,2)):
... print i
...
9
7
5
3
1
>>> basket = ['apple','orange','apple','pear','orange','banana']
>>> for f in sorted(set(basket)):
... print f
...
apple
banana
orange
pear
数据结构(Data Structures)的更多相关文章
- 无锁数据结构(Lock-Free Data Structures)
一个星期前,我写了关于SQL Server里闩锁(Latches)和自旋锁(Spinlocks)的文章.2个同步原语(synchronization primitives)是用来保护SQL Serve ...
- [CareerCup] 10.2 Data Structures for Large Social Network 大型社交网站的数据结构
10.2 How would you design the data structures for a very large social network like Facebook or Linke ...
- 剪短的python数据结构和算法的书《Data Structures and Algorithms Using Python》
按书上练习完,就可以知道日常的用处啦 #!/usr/bin/env python # -*- coding: utf-8 -*- # learn <<Problem Solving wit ...
- Trainning Guide, Data Structures, Example
最近在复习数据结构,发现这套题不错,题目质量好,覆盖广,Data Structures部分包括Example,以及简单,中等,难三个部分,这几天把Example的做完了, 摘要如下: 通过这几题让我复 ...
- Python Tutorial 学习(五)--Data Structures
5. Data Structures 这一章来说说Python的数据结构 5.1. More on Lists 之前的文字里面简单的介绍了一些基本的东西,其中就涉及到了list的一点点的使用.当然,它 ...
- 20162314 《Program Design & Data Structures》Learning Summary Of The First Week
20162314 2017-2018-1 <Program Design & Data Structures>Learning Summary Of The First Week ...
- The Model represents your data structures.
w模型代表数据结构. https://www.codeigniter.com/userguide3/overview/mvc.html http://codeigniter.org.cn/user_g ...
- 【Python学习笔记】Coursera课程《Python Data Structures》 密歇根大学 Charles Severance——Week6 Tuple课堂笔记
Coursera课程<Python Data Structures> 密歇根大学 Charles Severance Week6 Tuple 10 Tuples 10.1 Tuples A ...
- Persistent and Transient Data Structures in Clojure
此文已由作者张佃鹏授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 最近在项目中用到了Transient数据结构,使用该数据结构对程序执行效率会有一定的提高.刚刚接触Trans ...
- [译]The Python Tutorial#5. Data Structures
[译]The Python Tutorial#Data Structures 5.1 Data Structures 本章节详细介绍之前介绍过的一些内容,并且也会介绍一些新的内容. 5.1 More ...
随机推荐
- 安迪的第一本字典 - set--sstream
#include <iostream> #include <string> #include <set> #include <sstream> usin ...
- OpenDayLight "Error executing command: java.lang.NullPointerException"问题解决
参考: Fedora 21 mostly working but NullPointerException at Karaf shell 在使用ODL的时候,安装功能组件时出现: Error exec ...
- Spring Boot的自动配置的原理
Spring Boot在进行SpringApplication对象实例化时会加载META-INF/spring.factories文件,将该配置文件中的配置载入到Spring容器. 1.1.1. ...
- Swoft 快速上手小贴士
IDE一定要装注解插件PHP Annotations Request和Response里的with...开头的方法会clone $this, 而不是修改本实体, 所以设置Cookie之类的时候要$re ...
- 你可能不知道的mouseover/mouseout mouseenter/mouseleave
mouseover与mouseenter 1. 触发时机 mouseover在被监听的节点与子节点上都会触发 mouseenter只在被监听的节点上触发 本质上是因为mouseenter不能冒泡 2. ...
- Art-Template模板引擎(原生写法与简洁写法)
模板引擎:把js数据转换成html需要的页面,这就是模板引擎需要做的事 • native原生语法 1. 准备数据 2. 把数据转化成html格式的字符串 使用模板引擎 artT ...
- 1-11 RHLE7-重定向和文件查找
在Linux 系统中,一切皆设备Linux系统中使用文件来描述各种硬件,设备资源等例如:以前学过的硬盘和分区,光盘等设备文件sda1 sr0============================ ...
- js中的真值和假值
大多数编程语言中,布尔值true和false仅仅表示true/false.JavaScript中,如'Hello‘这样的字符串值,也可以看做true. 以下是不同数据类型在JavaScript中是如何 ...
- 转:kafka入门
一.基本概念 介绍 Kafka是一个分布式的.可分区的.可复制的消息系统.它提供了普通消息系统的功能,但具有自己独特的设计. 这个独特的设计是什么样的呢? 首先让我们看几个基本的消息系统术语:Kafk ...
- 个人学习jQuery笔记
1.$(“#div1”).text()是获取id为div1的文本内容,也可以填充值 $(“#div1”).html() 是获取id 为div1的HTML内容值 也可以填充值 2.$(“#div1”)是 ...