一、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)的更多相关文章

  1. 无锁数据结构(Lock-Free Data Structures)

    一个星期前,我写了关于SQL Server里闩锁(Latches)和自旋锁(Spinlocks)的文章.2个同步原语(synchronization primitives)是用来保护SQL Serve ...

  2. [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 ...

  3. 剪短的python数据结构和算法的书《Data Structures and Algorithms Using Python》

    按书上练习完,就可以知道日常的用处啦 #!/usr/bin/env python # -*- coding: utf-8 -*- # learn <<Problem Solving wit ...

  4. Trainning Guide, Data Structures, Example

    最近在复习数据结构,发现这套题不错,题目质量好,覆盖广,Data Structures部分包括Example,以及简单,中等,难三个部分,这几天把Example的做完了, 摘要如下: 通过这几题让我复 ...

  5. Python Tutorial 学习(五)--Data Structures

    5. Data Structures 这一章来说说Python的数据结构 5.1. More on Lists 之前的文字里面简单的介绍了一些基本的东西,其中就涉及到了list的一点点的使用.当然,它 ...

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

  7. The Model represents your data structures.

    w模型代表数据结构. https://www.codeigniter.com/userguide3/overview/mvc.html http://codeigniter.org.cn/user_g ...

  8. 【Python学习笔记】Coursera课程《Python Data Structures》 密歇根大学 Charles Severance——Week6 Tuple课堂笔记

    Coursera课程<Python Data Structures> 密歇根大学 Charles Severance Week6 Tuple 10 Tuples 10.1 Tuples A ...

  9. Persistent and Transient Data Structures in Clojure

    此文已由作者张佃鹏授权网易云社区发布. 欢迎访问网易云社区,了解更多网易技术产品运营经验. 最近在项目中用到了Transient数据结构,使用该数据结构对程序执行效率会有一定的提高.刚刚接触Trans ...

  10. [译]The Python Tutorial#5. Data Structures

    [译]The Python Tutorial#Data Structures 5.1 Data Structures 本章节详细介绍之前介绍过的一些内容,并且也会介绍一些新的内容. 5.1 More ...

随机推荐

  1. 爬虫之动态HTML处理(Selenium与PhantomJS )

    Selenium Selenium是一个Web的自动化测试工具,最初是为网站自动化测试而开发的,类型像我们玩游戏用的按键精灵,可以按指定的命令自动操作,不同是Selenium 可以直接运行在浏览器上, ...

  2. 爬虫框架Scrapy之案例二

    新浪网分类资讯爬虫 爬取新浪网导航页所有下所有大类.小类.小类里的子链接,以及子链接页面的新闻内容. 效果演示图: items.py import scrapy import sys reload(s ...

  3. SpringMVC封装表单数据

    1.domain类 package com.xiaostudy.domain; public class User { private int id; private String username; ...

  4. 测试php语句执行时间

    $start = microtime(true); $elapsed = microtime(true) - $start; echo "That took $elapsed seconds ...

  5. Memcached flush_all 命令

    Memcached flush_all 命令用于用于清理缓存中的所有 key=>value(键=>值) 对. 该命令提供了一个可选参数 time,用于在制定的时间后执行清理缓存操作. 语法 ...

  6. Android 数据库 ObjectBox 源码解析

    一.ObjectBox 是什么? greenrobot 团队(现有 EventBus.greenDAO 等开源产品)推出的又一数据库开源产品,主打移动设备.支持跨平台,最大的优点是速度快.操作简洁,目 ...

  7. Spring Boot技术栈博客笔记(1)

    要实现的核心功能 用户管理 安全设置 博客管理 评论管理 点赞管理 分类管理 标签管理 首页搜索 核心技术 数据存储 随着spring3发布以来,spring团队减少使用xml配置的使用,采用大量约定 ...

  8. Decrypting OWIN Authentication Ticket

    参考:https://long2know.com/2015/05/decrypting-owin-authentication-ticket/ AuthServer产生的Token因为没有制定自定义的 ...

  9. winform版本自动更新

    我们在使用软件的时候经常会遇到升级版本,这也是Winform程序的一个功能,今天就大概说下我是怎么实现的吧(代码有点不完美有小BUG,后面再说) 先说下我的思路:首先在打开程序的时候去拿到我之前在网站 ...

  10. Eclipse创建Maven聚合项目

    整体架构图 1.新建父工程 新建maven父项目(用来管理jar包版本),使子系统使用同一个版本的jar包. File->New->Other->Maven Project,打包方式 ...