设为首页 收藏本站
查看: 913|回复: 0

[经验分享] python 教程 第七章、 数据结构

[复制链接]

尚未签到

发表于 2015-4-21 12:29:14 | 显示全部楼层 |阅读模式
  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) #

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

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-59238-1-1.html 上篇帖子: Node.js能让Javascript写后端,为啥不让Python写前端? 下篇帖子: Python快速学习02:基本数据类型 & 序列
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表