###########字典dict############
1.为什么需要字典类型?
>>> list1 = ["name", "age", "gender"]
>>> list2 = ["fentiao", 5, "male"]
>>> zip(list1, list2) //通过zip内置函数将两个列表结合,help(zip)
[(‘name‘, ‘fentiao‘), (‘age‘, 5), (‘gender‘, ‘male‘)]
>>> list2[0] //在直接编程时,并不能理解第一个索引表示姓名
‘fentiao‘
>>> list2[name]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str
故字典是python中唯一的映射类型,key-value(哈希表),字典对象是可变的,但key必须用不可变对象。
2.字典的定义
In [8]: dic = {"name":"linux","age":22} #######定义一个字典
In [10]: dic["name"] //根据key找出value值,不能通过索引寻找value值
Out[10]: ‘linux‘
In [11]: dic["age"]
Out[11]: 22
############################################################
In [12]: user = [‘westos‘,‘linux‘] ##########定义列表
In [13]: passwd=[‘redhat‘,‘blue‘]
In [14]: zip(user,passwd) //通过zip内置函数将两个列表结合,help(zip
Out[14]: [(‘westos‘, ‘redhat‘), (‘linux‘, ‘blue‘)]
""""""
""""""
In [15]: dic={‘westos‘:‘redhat‘,‘linux‘:‘blue‘}
In [16]: dic[‘westos‘] //根据key找出value值
Out[16]: ‘redhat‘
In [17]: dic[‘westos‘] ==‘redhat‘ 判断key对应的value值字典中知否存在?存在返回Ture
Out[17]: True
3.字典的添加:
In [18]: dic={‘westos‘:‘redhat‘,‘linux‘:‘blue‘}
In [19]: dic[‘xiaobai‘]=‘123‘ ####key值和value值都不一样,整个添加。
In [20]: dic
Out[20]: {‘linux‘: ‘blue‘, ‘westos‘: ‘redhat‘, ‘xiaobai‘: ‘123‘}
In [21]: dic[‘linux‘]=‘block‘ ########key值一样和value值都不一样;将key对应的value值更新。
In [22]: dic
Out[22]: {‘linux‘: ‘block‘, ‘westos‘: ‘redhat‘, ‘xiaobai‘: ‘123‘}
4.字典的常用命令
In [23]: dic={‘westos‘:‘redhat‘}
In [24]: dic1={‘linux‘:‘blue‘}
In [25]: dic.
dic.clear dic.items dic.pop dic.viewitems
dic.copy dic.iteritems dic.popitem dic.viewkeys
dic.fromkeys dic.iterkeys dic.setdefault dic.viewvalues
dic.get dic.itervalues dic.update
dic.has_key dic.keys dic.values
In [25]: dic.update(dic1)###############添加更新,####key值和value值都不一样,整个添加
In [26]: dic
Out[26]: {‘linux‘: ‘blue‘, ‘westos‘: ‘redhat‘}
In [27]: dic={‘westos‘:‘redhat‘}
In [28]: dic1={‘westos‘:‘blue‘}
In [29]: dic.update(dic1) #### ######3key值一样和value值都不一样;将key对应的value值更新
In [30]: dic
Out[30]: {‘westos‘: ‘blue‘}
###########
因为字典是无序的,所以没有索引和切片。
###############################################################
In [31]: dic={‘westos‘:‘redhat‘,‘linux‘:‘blue‘}
In [32]: dic.pop(‘westos‘) #######删除,必须加key值;
Out[32]: ‘redhat‘ #########弹出字典中key值为"westos"的元素并返回该key的元素
In [33]: dic
Out[33]: {‘linux‘: ‘blue‘}
In [35]: dic={‘westos‘:‘redhat‘,‘linux‘:‘blue‘}
In [36]: dic.popitem() #######删除,不加key值,随机删除
Out[36]: (‘westos‘, ‘redhat‘)
In [37]: dic
Out[37]: {‘linux‘: ‘blue‘}
In [38]: dic.popitem()
Out[38]: (‘linux‘, ‘blue‘)
In [39]: dic
Out[39]: {}
In [40]: dic.popitem() #######key值删除完了,再删会报错
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-40-b472158de449> in <module>()
----> 1 dic.popitem()
KeyError: ‘popitem(): dictionary is empty‘
>>> dic.clear() //删除字典的所有元素
>>> dic
>>> del dic //删除整个字典
>>> dic
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name ‘dic‘ is not defined
##########################################################
In [47]: dic={‘westos‘:‘redhat‘,‘linux‘:‘blue‘}
In [48]: dic.values() ##########显示value值
Out[48]: [‘redhat‘, ‘blue‘]
In [49]: dic.keys() ##########显示key值
Out[49]: [‘westos‘, ‘linux‘]
In [50]: dic.get("westos") ############查看key值对应的value值(有)
Out[50]: ‘redhat‘
In [51]: dic.get("hello")############查看key值对应的value值(没有的情况下,返回值为none)
In [52]: print dic.get("hello")
None
In [53]: dic.has_key("hello") ######查看key值存在否?不存在显示False
Out[53]: False
In [54]: dic.has_key("linux") ######查看key值存在否?存在显示 True
Out[54]: True
>> ddict = {}.fromkeys((‘username‘,‘password‘),‘fentiao‘)
//字典中的key有相同的value值,默认为None
>>> ddict
{‘username‘: ‘fentiao‘, ‘password‘: ‘fentiao‘}
>>> ddict = {}.fromkeys((‘username‘,‘password‘),)
>>> ddict
{‘username‘: None, ‘password‘: None}
###################字典的去重功能##########
In [57]: dic.fromkeys(‘westos‘)
Out[57]: {‘e‘: None, ‘o‘: None, ‘s‘: None, ‘t‘: None, ‘w‘: None}
In [58]: dic.fromkeys(‘westos‘,‘hello‘)
Out[58]: {‘e‘: ‘hello‘, ‘o‘: ‘hello‘, ‘s‘: ‘hello‘, ‘t‘: ‘hello‘, ‘w‘: ‘hello‘}
In [59]: dic = {‘westos‘:‘redhat‘,‘westos‘:‘234‘}
In [60]: dic
Out[60]: {‘westos‘: ‘234‘}
###############访问字典的值:直接通过key访问,循环遍历字典的遍历##########
In [76]: dic = {1:‘a‘,2:‘2‘}
In [78]: for key in dic.keys(): ########## 建立函数dic.keys()
....: print "key=%s" % key
....:
key=1
key=2
In [79]: for value in dic.values():########### 建立函数 dic.values()
....: print "value=%s" % value
....:
value=a
value=2
In [81]: for key, value in dic.keys(), dic.values():##### 建立dic.keys()和 dic.values()函数
print "%s = %s" %(key,value)
....:
1 = 2
a = 2
In [83]: dic.items()
Out[83]: [(1, ‘a‘), (2, ‘2‘)]
In [86]: for k,v in dic.items():
print "%s = %s" %(k,v)
....:
1 = a
2 = 2
####################嵌套赋值###############################
In [92]: data = [‘fentiao‘,‘50‘,‘1000‘,(2017,12,31)]
In [93]: name,shares,juankuan,data = data
In [94]: print name,shares,juankuan,data
fentiao 50 1000 (2017, 12, 31)
"""""""""""""""""""""""""""""""""""""""""""""""""""""
In [97]: data = [‘fentiao‘,‘50‘,‘1000‘,(2017,12,31)]
In [98]: name,shares,juankuan,(year,month,day)= data
In [99]: print name,shares,juankuan,(year,month,day)
fentiao 50 1000 (2017, 12, 31)
In [100]: print year
2017
In [101]: print month
12
In [102]: print day
31
In [103]: data = [‘fentiao‘,‘50‘,‘1000‘,(2017,12,31)]
In [104]: name,_,_,_, = data #####不想使用的数据key值用"_"代替。
In [105]: print name
fentiao
#######################################
习题1:
对列表li = [34,45,32,132,43,55,],排序,去除最大值,最小值,求平均值。
In [106]: li = [34,45,32,132,43,55,]
In [107]: li.sort()
In [108]: li
Out[108]: [32, 34, 43, 45, 55, 132]
In [109]: li.pop(0)
Out[109]: 32
In [110]: li.pop(len(li)-1)
Out[110]: 132
In [111]: li
Out[111]: [34, 43, 45, 55]
In [112]: sum(li)/len(li)
Out[112]: 44
习题2:
代码:四则运算:
from __future__ import division
number1 = input("num1=")
operate = raw_input("operate=")
number2 = input("num2=")
dic ={"+":number1+number2,"-":number1-number2,"*":number1*number2,"/":number1/number2}
if operate in dic.keys():
print dic[operate]
截图:
###############函数################
1.定义函数
def关键字,依次写出函数名、括号、括号中的参数和冒号 :
在缩进块中编写函数体,函数的返回值用 return 语句返回。
2.函数的用法:
(1)函数在执行过程中一旦遇到return,函数就执行完毕,并将结果返回。
def hello():
return ‘hello‘
print ‘fentiao‘
print hello()
截图:
(2)函数在执行过程中没有遇到return,返回值None
def hello():
print ‘hello‘
print hello()
截图:
(3)如果要定义一个什么也不做的空函数时,可以用pass语句,作为一个占符位,让代码运行起来。
截图:前后对比,了解pass的功能。
(4)函数的参数检查:
abs求x的绝对值:
代码1:
def myabs(x):
if isinstance(x,(int,float)):
print abs(x)
else:
print "请输入整形或浮点型"
myabs(123)
myabs("m‘")
截图:
代码2:
def myabs(x):
if not isinstance(x,(int,float)):
print "请输入整形或浮点型"
return abs(x)
print myabs(123)
print myabs("m‘")
截图:
(5)函数返回多个值,实质上是返回一个元组tuple,返回时元组可以省略括号。
题目:定义一个函数func,传入两个数字,返回两个数字的最大值与平均值。
代码:
def func(x,y):
if not isinstance(x,int) or not isinstance(y,int):
print "type error"
avg = sum((x,y))/2
maxnum = max(x,y)
return "平均值:[%d]\n最大值:[%d]" %(avg,maxnum)
print func(2,10)
a截图:
b截图:验证返回值是一个元组tuple
(6)函数调用接受返回值时,按照位置赋值给变量。
代码:
ef func(x,y):
if not isinstance(x,int) or not isinstance(y,int):
print "type error"
avg = sum((x,y))/2
maxnum = max(x,y)
return (avg,maxnum)
myavg,mymax= func(2,10)
print mymax,myavg
截图:对比两张图,了解函数调用接受返回值时,按照位置赋值给变量。
3.参数:
参数定义的顺序:优先权力
必选参数>默认参数>可变参数>关键字参数
#######**kwargs包装字典,关键字参数,kwargs接受的是字典
######*args包装元组 ,可变参数。args接受的是元组
(1)默认参数,必选参数同时在函数中存在时,一定要必选参数放到前面。
(2)设置默认参数时,把变化大的参数放到前面,变化小的参数放后面,变化小的参数可以设置为默认参数。
引入问题:x的平方到x的n次方:
截图:
注意:当定义power时n=2放到x之前会报错,
原因是:默认参数,必选参数同时在函数中存在时,一定要必选参数放到前面。x是必选参数
截图:
练习1:
代码:
def yunwei(name,age=22,school="西安邮电"):
print ‘name:‘ +name
print ‘age: %d‘ %age
print ‘school:‘ + school
print yunwei(‘xiaobai‘)
print yunwei("xiaohuang" ,18,"西安财经")
截图:
练习2:
截图:
默认参数必须是不可变数据类型:
代码1:
def fun(li=None):
if li is None:
return[‘END‘]
li.append(‘END‘)
return li
print fun([1,2,3])
print fun()
截图:
代码2:
def fun1(li=[]):
if len(li) ==0:
return[‘END‘]
li.append(‘END‘)
return li
print fun1([2,3,4])
print fun1()
截图:
(3)可变参数
代码:
def fun (*args):
print type(args)
return max(args),min(args)
li = 1,43,23,12,2,7
print fun (*li)
截图:
(4)关键字参数
代码1:
def yunwei(name,age=22,**kwargs):
print ‘name:‘ +name
print ‘age: %d‘ %age
for k,w in kwargs.items():
print ‘%s :%s‘%(k,w)
print type (kwargs)
yunwei("fentiao")
yunwei("xiaobao" ,school= "youdian")
截图:
代码2:
def yunwei(name,age=22,**kwargs):
print ‘name:‘ +name
print ‘age: %d‘ %age
for k,w in kwargs.items():
print ‘%s :%s‘%(k,w)
print type (kwargs)
dic ={"school":"邮电","adresss":"西安"}
print yunwei("fentiao" ,**dic)
截图: