《转》python 9 字典,numpy

http://www.cnblogs.com/BeginMan/p/3156960.html

一、映射类型

我理解中的映射类型是:键值对的关系,键(key)映射值(value),且它们是一对多的关系。

字典是Python唯一的映射类型。

扩展1:哈希表

一种数据结构,值是根据相关的键进行数据存储的,形成"键-值对"(key-value pairs),哈希表中的值是没有顺序的。

扩展2:映射类型与序列类型的区别

1):访问方式不同,序列类型用数字类型的键,而映射类型可以用其他对象类型做键(一般式字符串)

《转》python 9 字典,numpy

>>> lis = ['a','b','c']
>>> lis[2]
'c'
>>> dic = {'name':'a','father':'b','mother':'c'}
>>> dic['mother']
'c'

《转》python 9 字典,numpy

2):存储类型不同,映射类型的键,直接或间接地与值相关。

3):序列类型,有序之列;映射类型则无序之列

二、字典

1、工厂方法dict():

《转》python 9 字典,numpy

>>> tu=(['a','b'],['xx','yy'])
>>> tu
(['a', 'b'], ['xx', 'yy'])
>>> fdict = dict(tu)
>>> fdict
{'a': 'b', 'xx': 'yy'}

《转》python 9 字典,numpy

2、访问形式:

《转》python 9 字典,numpy

>>> dic
{'father': 'b', 'name': 'a', 'mother': 'c'}
>>> for obj in dic:
      print obj

father
name
mother
>>> for obj in dic.keys():
      print obj

    
father
name
mother
>>> for obj in dic.values():
      print obj

    
b
a
c
>>> for obj in dic.items():
      print obj

    
('father', 'b')
('name', 'a')
('mother', 'c')
>>> 

《转》python 9 字典,numpy

3、has_key()、in、not in来检查是否有某个键,has_key()已慢慢弃用了。

4、有则更新,无则添

5、删除

del dic['name']   #删除元素
del dic #删除整个

6、操作符

[]、和 in、not in

>>> if 'name' in dic:
      print dic['name']
a

7、相关函数

dict():创建字典

len():返回键值对数目

hash(obj):返回obj的哈希值

8、内建方法

dict.clear():删除字典中所有元素

dict.copy():浅copy

dict.formkeys():创建字典

dict.get(key,default=None):返回对应键值

dict.has_key():键是否存在

dict.items():返回字典中键值对元祖的列表

dict.keys():键的列表dict.values():值的列表

......

《转》python 9 字典,numpy

>>> dic.keys()
['father', 'name', 'mother']
>>> dic.values()
['b', 'a', 'c']
>>> dic.get('name')
'a'

《转》python 9 字典,numpy

三、注意

1、不允许一个键对应多个值,一个键只能对应一项

2、当键发生冲突时,取最后一个。

3、Python不会检查键的冲突,也不会因为键的冲突而产生错误,如果检查每个键是否冲突势必会占用很多内存。

>>> dic={'a':'ss','a':"xxxx"}
>>> dic
{'a': 'xxxx'}

4、键必须是可哈希的。

所有不可变类型都是可哈希的,不可变类型如(列表、字典)则不能。

不可变类型:string,integer,tuple、

可变类型:list,dict

5、值相同的数字表示相同的键,如1和1.0的哈希值是相同的,因此它们是相同的键。

>>> dic={1:'a',1.0:'b'}
>>> dic
{1: 'b'}

(1)字典

字典是一种映射关系:键(key),值(value),key-value对

创建字典的方式:直接创建和利用dict函数创建

>>> aInfo = {'Wangdachui': 3000, 'Niuyun':2000, 'Linling':4500, 'Tianqi':8000}
>>> info = [('Wangdachui',3000), ('Niuyun',2000), ('Linling',4500), ('Tianqi',8000)]
>>> bInfo = dict(info)
>>> cInfo = dict([['Wangdachui',3000], ['Niuyun',2000], ['Linling',4500], ['Tianqi',8000]])
>>> dInfo = dict(Wangdachui=3000, Niuyun=2000, Linling=4500, Tianqi=8000)

《转》python 9 字典,numpy

>>> aDict = {}.fromkeys(('Wangdachui', 'Niuyun', 'Linling', 'Tianqi'),3000)
>>> aDict
{'Tianqi': 3000, 'Wangdachui': 3000, 'Niuyun': 3000, 'Linling': 3000}
>>> sorted(aDict)
['Linling', 'Niuyun', 'Tianqi', 'Wangdachui']
>>>names = ['Wangdachui', 'Niuyun', 'Linling', 'Tianqi']
>>>salaries = [3000, 2000, 4500, 8000]
>>>print(dict(zip(names,salaries)))
{'Niuyun': 2000, 'Linling': 4500, 'Tianqi': 8000, 'Wangdachui': 3000}

《转》python 9 字典,numpy

字典的基本操作:增删改查

《转》python 9 字典,numpy

>>> aInfo = {'Wangdachui': 3000, 'Niuyun':2000, 'Linling':4500, 'Tianqi':8000}
>>> aInfo['Niuyun']    #键值查找
5000
>>> aInfo['Niuyun'] = 9999          #更新
>>> aInfo
{'Tianqi': 8000, 'Wangdachui': 3000, 'Linling': 4500, 'Niuyun': 9999}
>>> aInfo['Fuyun'] = 1000      #添加
>>> aInfo
{'Tianqi': 8000, 'Fuyun': 1000, 'Wangdachui': 3000, 'Linling': 4500, 'Niuyun': 9999}
>>> 'Mayun' in aInfo        #成员判断
False
>>> del aInfo       #删除字典
>>> aInfo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'aInfo' is not defined

《转》python 9 字典,numpy

字典的格式化字符串:

《转》python 9 字典,numpy

>>> aInfo = {'Wangdachui': 3000, 'Niuyun':2000, 'Linling':4500, 'Tianqi':8000}
>>> for key in aInfo.keys():
print 'name=%s, salary=%s' % (key, aInfo[key])      #  %(key)格式说明符 % 字典对象名>>> "Niuyun's salary is %(Niuyun)s." % aInfo
"Niuyun's salary is 5000."

《转》python 9 字典,numpy

输出模板的作用

《转》python 9 字典,numpy

>>> aInfo = {'Wangdachui': 3000, 'Niuyun':2000, 'Linling':4500, 'Tianqi':8000}
>>> template = '''
Welcome to the pay wall.
Niuyun's salary is %(Niuyun)s.
Wangdachui's salary is %(Wangdachui)s.
'''
>>> print template % aInfo
Welcome to the pay wall. Niuyun's salary is 2000. Wangdachui's salary is 3000.

《转》python 9 字典,numpy

字典的方法

clear() fromkeys()

get() has_key ()

items() pop()

setdefault() update()

values() copy()

(2)集合:无序不重复的元素的集合

可变集合:set

>>> names = ['Wangdachui', 'Niuyun', 'Wangzi', 'Wangdachui', 'Linling', 'Niuyun']
>>> namesSet = set(names)
>>> namesSet
{'Wangzi', 'Niuyun', 'Wangdachui', 'Linling'

不可变集合:frozenset

《转》python 9 字典,numpy

aSet = set('hello')
print(aSet)
fSet = frozenset('hello')
print(fSet)
{'e', 'l', 'h', 'o'}
frozenset({'e', 'l', 'h', 'o'})

《转》python 9 字典,numpy

集合比较和关系运算符和集合操作

《转》python 9 字典,numpy《转》python 9 字典,numpy《转》python 9 字典,numpy《转》python 9 字典,numpy

(3)python常用的数据结构

ndarray(N维数组)

Series(变长字典)

DataFrame(数据框)

《转》python 9 字典,numpy

import numpy as np
xArray = np.ones((3,4))
print(xArray)

[[ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]
 [ 1.  1.  1.  1.]]

《转》python 9 字典,numpy

ndarray:

NumPy中基本的数据结构

别名为array

利于节省内存和提高CPU计算时间

有丰富的函数

ndarray的创建和输出

《转》python 9 字典,numpy

>>> from numpy import *
>>> aArray = array([1,2,3])
>>> aArray
array([1, 2, 3])
>>> bArray = array([(1,2,3),(4,5,6)])
>>> bArray
array([[1, 2, 3],
[4, 5, 6]])
>>> zeros((2,2))
array([[ 0., 0.],
[ 0., 0.]])
>>> arange(1,5,0.5)
array([ 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5])

《转》python 9 字典,numpy

ndarray的基本运算符

《转》python 9 字典,numpy

>>> aArray = array([(5,5,5),(5,5,5)])
>>> bArray = array([(2,2,2),(2,2,2)])
>>> cArray = aArray * bArray
>>> cArray
array([[10, 10, 10],
[10, 10, 10]])
>>> aArray += bArray
>>> aArray
array([[7, 7, 7],
[7, 7, 7]])
>>> aArray > 5
array([[ True, True, True],
[True, True, True]], dtype=bool)

《转》python 9 字典,numpy

ndarray的属性和方法

《转》python 9 字典,numpy

>>> aArray = array([(1,2,3),(4,5,6)])
>>> aArray.shape
(2, 3)
>>> bArray = aArray.reshape(3,2)
>>> bArray
array([[1, 2],
[3, 4],
[5, 6]])
>>> aArray.sum()
21
>>> aArray.sum(axis = 0)
array([5, 7, 9])
>>> aArray.sum(axis = 1)
array([ 6, 15])
>>> aArray = array([1,3,7])
>>> bArray = array([3,5,8])
>>> cArray = array([9,8,7])
>>> aArray[1:]
array([3, 7])
>>> where(aArray>2, bArray, cArray)
array([9, 5, 8]

《转》python 9 字典,numpy

ndarray的内建函数

《转》python 9 字典,numpy

>>> def fun(x,y):
return (x+1)*(y+1)
>>> arr = fromfunction(fun,(9,9))
>>> arr
array([[ 1., 2., 3., 4., 5., 6., 7., 8., 9.], [ 2., 4., 6., 8., 10., 12., 14., 16., 18.], [ 3., 6., 9., 12., 15., 18., 21., 24., 27.], [ 4., 8., 12., 16., 20., 24., 28., 32., 36.], [ 5., 10., 15., 20., 25., 30., 35., 40., 45.], [ 6., 12., 18., 24., 30., 36., 42., 48., 54.], [ 7., 14., 21., 28., 35., 42., 49., 56., 63.], [ 8., 16., 24., 32., 40., 48., 56., 64., 72.], [ 9., 18., 27., 36., 45., 54., 63., 72., 81.]])

《转》python 9 字典,numpy

ndarray的ufunc函数

《转》python 9 字典,numpy

import numpy as np
>>> a = np.arange(1,5)
>>> a
array([1, 2, 3, 4])
>>> b = np.arange(2,6)
>>> b
array([2, 3, 4, 5])
>>> np.add(a,b)
array([3, 5, 7, 9])
>>> np.add.accumulate([2, 3, 8])
array([ 2, 5, 13])
>>> np.multiply.accumulate([2, 3, 8])
array([ 2, 6, 48])
Source
help(ufunc)
help(numpy)
add = <ufunc 'add'>