Python中有三种内建的数据结构——列表、元组和字典。
1)    Lists列表 [,]
列表是序列的一种

shoplist = ['apple', 'carrot', 'banana']
print shoplist #['apple', 'carrot', 'banana']
shoplist.append('orange') #末尾加入一个
print shoplist #['apple', 'carrot', 'banana', 'orange']
shoplist.insert(2, 'flint') #指定位置插入
print shoplist #['apple', 'carrot', 'flint', 'banana', 'orange']
shoplist.reverse() #反转
print shoplist #['orange', 'banana', 'flint', 'carrot', 'apple']
shoplist.pop() #默认从末尾删除
print shoplist #['orange', 'banana', 'flint', 'carrot']
shoplist.sort() #正向排序
print shoplist #['banana', 'carrot', 'flint', 'orange']
del shoplist[1] #指定位置删除,等于shoplist.pop(1)
print shoplist #['banana', 'flint', 'orange']
shoplist.extend(['database', 'egg']) #末尾加入多个
print shoplist #['banana', 'flint', 'orange', 'database', 'egg']
shoplist.remove('banana') #删除指定项
print shoplist #['flint', 'orange', 'database', 'egg']

通过help(list)获得完整的知识。

列表解析表达式
从一个已有的列表导出一个新的列表。

vec = [2, 4, 6]
print (3 * x for x in vec) #<generator object <genexpr> at 0x00E7D300>
print list(3 * x for x in vec) #[6, 12, 18]
print [3 * x for x in vec] # [6, 12, 18]
print [3 * x for x in vec if x > 3] # [12, 18]
print [3 * x for x in vec if x < 2] # []
print [[x, x**2] for x in vec] # [[2, 4], [4, 16], [6, 36]]
M = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print [row[1] for row in M] # [2, 5, 8]
print [row[1] for row in M if row[1] % 2 == 0] #[2, 8]

print [x + y for x in 'abc' for y in 'mn'] #['am', 'an', 'bm', 'bn', 'cm', 'cn'] 

处理大型矩阵使用开源NumPy系统

Nesting嵌套

M = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print M #[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print M[0] #[1, 2, 3]
print M[1][2] #6 

列表解析

>>> list(map(sum, M)) #[6, 15, 24]
>>> {sum(row) for row in M} #set([24, 6, 15])
>>> {x: ord(x) for x in 'spabm'} #{'a': 97, 'p': 112, 's': 115, 'b': 98, 'm': 109} 

索引操作符
索引操作符,下标操作,从0开始,支持反向索引,从-1开始

>>> sp = ['a', 'b', 'c', 'd']
>>> sp[0], sp[1], sp[2], sp[3] #('a', 'b', 'c', 'd')
>>> sp[-4], sp[-3], sp[-2], sp[-1] #('a', 'b', 'c', 'd')
>>> name = 'swaroop'
>>> len(name) #7
>>> name[-1] #'p'
>>> name[len(name) - 1] #'p' 

切片操作符X[I:J]
切片(slice)操作符,序列名跟方括号,方括号中有一对可选的数字,并用冒号分割。数是可选的,而冒号是必须的。
X[I:J],取出在X中从偏移为I,直到但不包括J的内容

>>> shoplist = ['a', 'b', 'c', 'd']
>>> shoplist[1:3] #['b', 'c']
>>> shoplist[2:] #['c', 'd']
>>> shoplist[1:-1] #['b', 'c']
>>> shoplist[:] #['a', 'b', 'c', 'd']
name = 'swaroop'
>>> name[1:3] # wa,不包括r!
>>> name[2:] # aroop
>>> name[1:-1] # waroo
>>> name[:] # swaroop
>>> name * 2 # swaroopswaroop 

三元切片操作符X[I:J:K]

X[I:J] = X[I:J:1]
s = "abcdefghijklmn"
print s[1:10:2] #bdfhj
print s[::2] #acegikm
print s[::-2] #nljhfdb 

参考

shoplist = ['apple', 'mango', 'carrot', 'banana']
mylist = shoplist # mylist is just another name pointing to the same object!
del shoplist[0]
print shoplist # ['mango', 'carrot', 'banana']
print mylist # ['mango', 'carrot', 'banana']
mylist = shoplist[:] # make a copy by doing a full slice
del mylist[0] # remove first item
print shoplist # ['mango', 'carrot', 'banana']
print mylist # ['carrot', 'banana']

如果要复制列表或者序列或者对象,那么你必须使用切片操作符来取得拷贝。记住列表的赋值语句不创建拷贝

浅拷贝深拷贝
浅拷贝(1)完全切片操作[:];(2)利用工厂函数,如list(),dict();(3)使用copy模块的copy函数
深拷贝(1)使用copy模块的deepcopy()函数

模拟堆栈

stack = []
def pushit():
    stack.append(raw_input("Enter new String:").strip())
def popit():
    if len(stack) == 0:
        print 'Can not pop from an empty stack!'
    else:
        print 'Removed [', stack[-1], ']'
        stack.pop()
def viewstack():
    print stack
CMDs = {'u':pushit, 'o':popit, 'v':viewstack}
def showmenu():
    pr = """p(U)sh  p(O)p (V)iew (Q)uit  Enter choice:"""
    while True:
        while True:
            try:
                choice = raw_input(pr).strip()[0].lower()
            except (EOFError, KeyboardInterrupt, IndexError):
                choice = 'q'
            print '\nYou picked: [%s]' %choice
            if choice not in 'uovq':
                print 'Invalid option, try again'
            else:
                break
        if choice == 'q':
            break
        CMDs[choice]()

if __name__ == '__main__':
showmenu()

2)    Tuples元组(,)
元组是不可变的 即不能修改。元组通过圆括号中用逗号分割的项目定义。

zoo = ('w', 'e', 'p')
new_zoo = ('m', 'd', zoo)
print zoo #('w', 'e', 'p')
print new_zoo #('m', 'd', ('w', 'e', 'p'))
print new_zoo[2] #('w', 'e', 'p')
print new_zoo[2][2] #p
new_zoo[1] = 'x' #TypeError: 'tuple' object does not support item assignment

元组最通常的用法是用在打印语句中

age = 22
name = 'Swaroop'
print '%s is %d years old' % (name, age)
print 'Why is %s playing with that python?' % name 

print语句使用跟着%符号的项目元组的字符串。定制输出满足某种特定的格式。定制可以是%s表示字符串或%d表示整数。

3)    Dictionaries字典{k:v}
键值对:d = {key1 : value1, key2 : value2 }

rec = {'name': {'first': 'Bob', 'last': 'Smith'}, 'job': ['dev', 'mgr'], 'age': 40.5}
print rec['name'] #{'last': 'Smith', 'first': 'Bob'}
print rec['name']['last'] #'Smith'
print rec['job'] #['dev', 'mgr']
print rec['job'][-1] #'mgr'
rec['job'].append('janitor')
print rec #{'age': 40.5, 'job': ['dev', 'mgr', 'janitor'], 'name': {'last': 'Smith', 'first': 'Bob'}}

print rec.keys() #['age', 'job', 'name']
print rec.values() #[40.5, ['dev', 'mgr', 'janitor'], {'last': 'Smith', 'first': 'Bob'}]
print rec.items() #[('age', 40.5), ('job', ['dev', 'mgr', 'janitor']), ('name', {'last': 'Smith', 'first': 'Bob'})] 

Sorting Key:

>>> D = {'a': 1, 'b': 2, 'c': 3}
>>> sorted(D) #['a', 'b', 'c']
D = {'a': 1, 'c': 3, 'b': 4}
for k in sorted(D.keys()): print(k, D[k])
for k in sorted(D): print(k, D[k]) #('a', 1) ('b', 4) ('c', 3) 

Missing Key:

>>> value = D.get('x', 0)
>>> value #0
>>> value = D['x'] if 'x' in D else 0
>>> value #0 

Other Ways

d = dict(zip(['a', 'b', 'c'], [1, 2, 3]))
print d # {'a': 1, 'c': 3, 'b': 2}
D = {c: c * 4 for c in 'SPA'}
print D #{'A': 'AAAA', 'P': 'PPPP', 'S': 'SSSS'}

使用help(dict)来查看dict类的完整方法列表。

4)    set集合()

a = set('abracadabra')
b = set('alacazam')
Y = {'h', 'a', 'm'} #python3
print a # unique letters in a
print a - b # letters in a but not in b
print a | b # letters in either a or b
print a & b # letters in both a and b
print a ^ b # letters in a or b but not both

python 教程 第七章、 数据结构的更多相关文章

  1. Objective-C 基础教程第七章,深入理解Xcode

    目录 Object-C 基础教程第七章,深入理解Xcode 0x00 前言 0x01 创建工程界面 0x02 主程序界面 ①顶部 Top Test(测试) Profile(动态分析) Analyze( ...

  2. 2017.2.12 开涛shiro教程-第七章-与Web集成

    2017.2.9 开涛shiro教程-第七章-与Web集成(一) 原博客地址:http://jinnianshilongnian.iteye.com/blog/2018398 根据下载的pdf学习. ...

  3. 2018-06-21 中文代码示例视频演示Python入门教程第五章 数据结构

    知乎原链 续前作: 中文代码示例视频演示Python入门教程第四章 控制流 对应在线文档: 5. Data Structures 这一章起初还是采取了尽量与原例程相近的汉化方式, 但有些语义较偏(如T ...

  4. python教程(七)·字典

    本文介绍本系列教程最后一个数据结构--字典 在现实生活中,查英语字典的时候,我们通常根据单词来查找意思.而python中的字典也是类似的,根据特定的 "键"(单词)来查找 &quo ...

  5. [ABP教程]第七章 作者:数据库集成

    Web开发教程7 作者:数据库集成 关于此教程 在这个教程系列中,你将要构建一个基于ABP框架的应用程序 Acme.BookStore.这个应用程序被用于甘丽图书页面机器作者.它将用以下开发技术: E ...

  6. Cobalt Strike系列教程第七章:提权与横向移动

    Cobalt Strike系列教程分享如约而至,新关注的小伙伴可以先回顾一下前面的内容: Cobalt Strike系列教程第一章:简介与安装 Cobalt Strike系列教程第二章:Beacon详 ...

  7. Flask 教程 第七章:错误处理

    本文翻译自The Flask Mega-Tutorial Part VII: Error Handling 这是Flask Mega-Tutorial系列的第七部分,我将告诉你如何在Flask应用中进 ...

  8. 进击的Python【第七章】:Python的高级应用(四)面向对象编程进阶

    Python的高级应用(三)面向对象编程进阶 本章学习要点: 面向对象高级语法部分 静态方法.类方法.属性方法 类的特殊方法 反射 异常处理 Socket开发基础 一.面向对象高级语法部分 静态方法 ...

  9. python教程(二)·数据结构初探

    这一节,我来简单讲讲python自带的数据结构. 列表(list) 列表是常用的python数据结构,类似于C语言的数组,用来存储多个元素,与之不同的是,C语言的数组中的元素的类型是相同的,而列表可以 ...

随机推荐

  1. blob-照片转换与展示

    File转java.sql.Blob(照片)Struts2 public Blob photos(File zp) { Blob photo=null; try { FileInputStream f ...

  2. Ubuntu 16.04下安装Anaconda

    1.下载Anaconda到系统 官网:https://www.anaconda.com/download/ 清华大学开源软件镜像站:https://mirrors.tuna.tsinghua.edu. ...

  3. 【t057】任务分配

    Time Limit: 1 second Memory Limit: 128 MB [问题描述] 现有n个任务,要交给A和B完成.每个任务给A或给B完成,所需的时间分别为ai和bi.问他们完成所有的任 ...

  4. [Angular Testing] Unit Testing -- Test component and service.

    Recommend to use angular-cli to generate component and service, so we can get testing templates. ng ...

  5. matlab 下的集成学习工具箱

    matlab 当前支持的弱学习器(weak learners)类型分别为: 'Discriminant' 'knn' 'tree' 可通过 templateTree 定义: 1. fitcensemb ...

  6. svn pre commit

    windows下的必须要用.bat文件,pre-commit.bat ================================================== @echo off set ...

  7. Warning: preg_replace(): Compilation failed: missing terminating ] for character class at offset 10 in

    Warning: preg_replace(): Compilation failed: missing terminating ] for character class at offset 10 ...

  8. 【codeforces 758C】Unfair Poll

    time limit per test1 second memory limit per test256 megabytes inputstandard input outputstandard ou ...

  9. Android中蓝牙的基本使用----BluetoothAdapter类简介

    天气逐渐热了,自己也越来越懒了,虽然看着了很多东西,解决了很多问题,有些收获却不想写着.主要有一下两方面原因: 第一.以前写的一些关于Android知识的Blog,都是在学习过程中发现网络上没有相关知 ...

  10. 二维高斯滤波器(gauss filter)的实现

    我们以一个二维矩阵表示二元高斯滤波器,显然此二维矩阵的具体形式仅于其形状(shape)有关: def gauss_filter(kernel_shape): 为实现二维高斯滤波器,需要首先定义二元高斯 ...