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. JNI——Java调用C/C++函数

    从C/C++到Java,再从Java回到C/C++,今天终于有机会了解了连接Java.C/C++的桥梁——JNI.哈哈!分享一下!   一.简介 JNI是Java native interface的简 ...

  2. vim :g

    https://stackoverflow.com/questions/1946738/vim-how-to-delete-every-second-row An elegant (and effic ...

  3. Android 各个版本号WebView

    转载请注明出处   http://blog.csdn.net/typename/ powered by miechal zhao : miechalzhao@gmail.com 前言: 依据Googl ...

  4. php解析xml字符串

    <?php $content = <<<XML <?xml version="1.0" encoding="UTF-8"?> ...

  5. 小强的HTML5移动开发之路(48)——(小练习)新闻订阅系统【1】

    一.总体设计 二.数据库设计 --新闻类别表 create table news_cate( news_cateid int primary key auto_increment, news_icon ...

  6. js如何使用正则表达式验证电话号码(可选区号)和邮箱?(分步骤)

    js如何使用正则表达式验证电话号码(可选区号)和邮箱?(分步骤) 一.总结 js进阶正则表达式16电话号码和邮箱正则(分类解决邮箱验证)(分组加?解决电话号码区号选择问题)([\w\.-]中括号解决邮 ...

  7. 【hdu 1846】Brave Game

    Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submission(s) ...

  8. [Angular] Dynamic component's instance and sorting

    After create a component dynamic, we are able to change the component's props and listen to its even ...

  9. 小强的HTML5移动开发之路(32)—— JavaScript回顾7

    BOM模型brower object model(浏览器对象模型),通过浏览器内置的一些对象可以操作浏览器本身. DOM是用来操作页面的,BOM是用来操作浏览器本身的. BOM是没有规范的,但是大部分 ...

  10. qt-4.8.4安装和环境变量配置

    在Linux中分别安装应用于不同平台的Qt:PC.嵌入式X86:ARM. 这三者PC版.嵌入式X86版和ARM版的差别主要体如今:当configure时分别加了不同的參数,详细差别是: PC平台(X1 ...