python 教程 第七章、 数据结构

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
posted @ 2011-10-13 11:23  方倍工作室  阅读(889)  评论(1编辑  收藏  举报