python基础3

简介:

python基础3


 交换:
a,b=b,a

相当于定义了一个元组t=(b,a)
然后将t[0]的值给了a,t[1]的值给了b





####字典####

定义用花括号

集合定义若为空的话,会默认为字典,所以集合不能为空




子典只能通过关键字来查找值,因为字典是key-value(关键字-值),因此不能通过值来查找关键字
In [1]: dic = {"user1":"123","user2":"234","user3":"789"}
In [3]: dic["234"]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-3-2845b64d96b1> in <module>()
----> 1 dic["234"]

KeyError: '234'




字典是一个无序的数据类型,因此也不能进行索引和切片等操作。
In [1]: dic = {"user1":"123","user2":"234","user3":"789"}

In [2]: dic["user1"]
Out[2]: '123'

In [5]: dic["user2"]
Out[5]: '234'



In [7]: user = ['user1','user2','user3']

In [8]: passwd = ['123','234','456']

In [9]: zip(user,passwd)
Out[9]: [('user1', '123'), ('user2', '234'), ('user3', '456')]

In [10]: 

当你有一个用户名单和密码,若使用列表的类型,判断用户是否和密码一致时,就比较麻烦,而使用字典时,只需通过关键子就可以返回相对应的值,(如上例子:当定义一个子典当你搜索user1时,字典类型就会返回该关键字对应的密码,此时只需判断该密码是否匹配即可)



####字典的基本操作###

In [17]: 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 [12]: dic
Out[12]: {'user1': '123', 'user2': '234', 'user3': '789'}

In [13]: dic["westos"]='linux'

In [14]: dic
Out[14]: {'user1': '123', 'user2': '234', 'user3': '789', 'westos': 'linux'}

In [15]: dic["hello"]='world'

In [16]: dic            ####由此可以看出字典是无序的,在添加时,并不会按照顺序往后添加####
Out[16]: 
{'hello': 'world',
 'user1': '123',
 'user2': '234',
 'user3': '789',
 'westos': 'linux'}

In [17]: 


字典更新


In [22]: dic
Out[22]: {'hello': 'world', 'user1': '123', 'user2': '234', 'user3': '789'}

In [23]: dic["user1"]="redhat"        ###可直接通过赋值对关键字进行更新###

In [24]: dic
Out[24]: {'hello': 'world', 'user1': 'redhat', 'user2': '234', 'user3': '789'}


###或者通过dic.update更新###
In [25]: dic
Out[25]: {'hello': 'world', 'user1': 'redhat', 'user2': '234', 'user3': '789'}

In [26]: help(dic.update)
Help on built-in function update:

update(...)
    D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
    If E present and has a .keys() method, does:     for k in E: D[k] = E[k]
    If E present and lacks .keys() method, does:     for (k, v) in E: D[k] = v
    In either case, this is followed by: for k in F: D[k] = F[k]
(END)


In [28]: dic1={'yunwei':"westos",'user1': 'redhat'}

In [29]: dic.update(dic)
dic   dic1  dict  

In [29]: dic.update(dic1)        ###将dic1中dic所没有的更新给了dic###

In [30]: dic
Out[30]: 
{'hello': 'world',
 'user1': 'redhat',
 'user2': '234',
 'user3': '789',
 'yunwei': 'westos'}

In [31]: 




####若是关键字相同,而值不同,就将值更新给他####

In [35]: dic
Out[35]: {'hello': 'world'}

In [36]: dic1
Out[36]: {'user1': 'redhat', 'yunwei': 'westos'}

In [37]: dic1["hello"]="hai"

In [38]: dic.update(dic1)

In [39]: dic
Out[39]: {'hello': 'hai', 'user1': 'redhat', 'yunwei': 'westos'}



In [42]: dic.clear()        ###清空dic###

In [43]: dic
Out[43]: {}

In [44]: del(dic)        ###删除dic###

In [45]: dic
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-45-1b445b6ea935> in <module>()
----> 1 dic

NameError: name 'dic' is not defined




####字典的删除####

In [49]: dic1
Out[49]: {'user1': 'redhat', 'yunwei': 'westos'}

In [50]: dic1.pop("user1")        ###指定关键字,删除该关键字和值####
Out[50]: 'redhat'

In [51]: dic1
Out[51]: {'yunwei': 'westos'}

In [52]: 



In [74]: dic1.popitem()        ###不指定关键字,随即删除###
Out[74]: ('yunwei', 'westos')



In [77]: dic = {"hello":"123","westos":"linux"}        

In [79]: dic.keys()        ###查看dic的全部关键字###
Out[79]: ['hello', 'westos']

In [80]: dic.values()        ###查看dic的全部值###
Out[80]: ['123', 'linux']



In [82]: dic.get("hello")    ###得到相对应的关键字的值,若关键字不存在,则默认返回none
Out[82]: '123'

In [83]: dic.get("redhat")

In [84]: print dic.get("redhat")
None


In [87]: dic.has_key("hello")        ###查看是否有该关键字,
Out[87]: True

In [88]: dic.has_key("world")
Out[88]: False


dict.fromkeys()            ###可以通过该操作实现去重###

In [89]: dic
Out[89]: {'hello': '123', 'westos': 'linux'}

In [90]: dic.fromkeys([1,2,3,4])
Out[90]: {1: None, 2: None, 3: None, 4: None}

In [91]: dic.fromkeys([1,2,3,4],'hello')
Out[91]: {1: 'hello', 2: 'hello', 3: 'hello', 4: 'hello'}


In [38]: d = {}
In [32]: li = [1,2,3,1,2,3]            ###去重###

In [33]: d.fromkeys(li)
Out[33]: {1: None, 2: None, 3: None}

In [34]: d.fromkeys(li).keys()
Out[34]: [1, 2, 3]



字典的key必须是不可变的数据类型


In [94]: dic = {1:'1',2:'2',1:'a'}

In [95]: dic
Out[95]: {1: 'a', 2: '2'}        ###一个关键字只能对应一个值###

In [96]: for key in dic.keys():        ###逐个遍历key###
   ....:     print "key=%s" % key 
   ....: 
key=1
key=2


In [97]: for value in dic.values():    ###逐个遍历value的值###
    print "value=%s" % value
   ....:     
value=a
value=2


In [98]: for key,value in dic.keys(),dic.values():    ###逐个遍历key -> value 的值#####
   ....:     print "%s -> %s" %(key,value)
   ....: 
1 -> 2
a -> 2




In [100]: dic
Out[100]: {1: 'a', 2: '2'}
In [101]: dic.items()            ###以元组的形式一一对应key和value的值###
Out[101]: [(1, 'a'), (2, '2')]

In [102]: for k,v in dic.items():
   .....:     print "%s -> %s" %(k,v)
   .....: 
1 -> a
2 -> 2


和list的比较,dict的不同:
1 查找和插入的速度快,字典不会随着key值的增加查找速度减慢
2 占用内存大,浪费空间



小练习:
去掉一个最高分和最低分,并且显示平均值

li = [90,91,67,100,89]


In [103]: li = [90,91,67,100,89]

In [104]: li.sort()        ###排序###

In [105]: li
Out[105]: [67, 89, 90, 91, 100]

In [106]: li.pop()
Out[106]: 100

In [107]: li.pop(0)
Out[107]: 67

In [108]: li
Out[108]: [89, 90, 91]

In [109]: sum(li)/len(li)    ###sum函数求和###
Out[109]: 90

小练习:用字典实现case语句:
!/usr/bin/env python
#coding:utf-8
from __future__ import division
num1 = input("num1:")
oper = raw_input('操作:')
num2 = input('num2:')

dic = {"+":num1+num2,"-":num1-num2,"*":num1*num2,'/':num1/num2}

if oper in dic.keys():
    print dic[oper]



#####函数####


函数名的理解:函数名与变量名类似,其实就是指向一个函数对象的引用;

            给这个函数起了一个“别名”:函数名赋给一个变量


In [5]: sum(li)
Out[5]: 6

In [6]: a = sum        ###将sum的函数名给了a变量,使得a能够进行求和###

In [7]: a(li)
Out[7]: 6

In [8]: 
In [8]: sum = abs

In [9]: sum(-1)
Out[9]: 1

In [10]: sum([2,4,5]    ###将abs的函数名给了sum,则sum就不再具有求和的功能###
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-10-d3c81a94a2a0> in <module>()
----> 1 sum([2,4,5])

TypeError: bad operand type for abs(): 'list'

In [11]: a([2,4,5])
Out[11]: 11



####函数的返回值###

def    hello():
    print "hello"

print hello()            ###该函数没有返回值,只是打印了hello,返回值为none


def    hello():
    return    ”hello“

print hello()            ###该函数有返回值,则返回一个hello###    


####函数在执行过程中一旦遇到return,就执行完毕并且将结果返回,如果没有遇到return,返回值为none###


###定义一个什么也不做的空函数,可以用pass语句,作为一个占位符使得代码先运行起来

def hello():
    return "hello"

def world():
    pass

print hello()
print world()


运行结果:
/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/10.py
hello
None

Process finished with exit code 0





小练习:将abs的错误显示进行优化###

def my_abs(x):
    if isinstance(x,(int,float)):    ###判断数据类型,是int或是float(也可以是别的类型,看你写的)###
     print   abs(x)
    else:
        print "请输入整型或浮点型的数"


my_abs("a")
my_abs(123)

执行结果:
/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/11.py
请输入整型或浮点型的数
123

Process finished with exit code 0




小练习:定义一个函数func(name),该函数效果如下:
func('hello')    -> 'Hello'
func('World')    -> 'World'

def func(name):
    print name.capitalize()
name = raw_input("name:")
func(name)


执行结果:
/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/12.py
name:hello
Hello

Process finished with exit code 0


函数的返回值,函数可以返回多个值
小练习:定义一个函数func,传入两个数字,返回两个数字的最大值和平均值


def func(x,y):
    if x>y:
        return x,(x+y)/2
    else:
        return y,(x+y)/2


x=6
y=3
print func(x,y)

执行结果:
/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/13.py
(6, 4)            ###由此可见,返回多个值,实际上是返回一个元组###

Process finished with exit code 0


###返回的元组的括号可以省略,函数调用接受返回值时,按照位置赋值变量###
def func(x,y):
    if x>y:
        return x,(x+y)/2
    else:
        return y,(x+y)/2


x=6
y=3
avg,maxnum = func(x,y)
print avg,maxnum

执行结果:
/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/13.py
6 4

Process finished with exit code 0


###函数的参数###
def power(x,n=2):    ###设定n默认为2,则n为默认参数,x为必选参数###
    return x**n
print power(2)


def power(x,n=2):
    return x**n
print power(2,4)    ###也可以进行多次操作###

####当默认参数和必选参数同时存在时,一定要将必选参数放在默认参数之前###

###设置默认参数时,把变化大的参数放前面,变化小的参数放后面,将变化小的参数设置为默认参数###

def enroll(name,age=22,myclass="westoslinux"):
    print 'name=%s'% name
    print 'age:%d'% age
    print 'class:%s' %myclass

enroll('user1')
enroll('user2',20)
enroll('user3',18,'全能班')

执行结果:
name=user1
age:22
class:westoslinux
name=user2
age:20
class:westoslinux
name=user3
age:18
class:全能班

Process finished with exit code 0


###默认参数必须使不可变的数据类型###
例:
先定义一个函数,传入一个 list,添加一个END 再返回

def fun(li=[]):
    li.append("END")
    return li
print fun([1,2,3])
print fun()
print fun()

执行结果:

/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/14.py
[1, 2, 3, 'END']
['END']
['END', 'END']        ###因为列表是可变的数据类型,所以在第二次输入print    fun()时,默认参数就不是空,而已经有了一个“END”###

Process finished with exit code 0




更改为:li=None,则此时li的默认值为不可变的数据类型


def fun(li=None):
    if li is None:
        return ['END']
    li.append('END')
    return li
print fun([1,2,3])
print fun()
print fun()


执行结果为:
/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/14.py
[1, 2, 3, 'END']
['END']
['END']

Process finished with exit code 0




####可变参数###
定义参数时,形参可以为*args,使函数可与接受多个参数;
如果想要将一个列表或者元组传入参数,也可以通过*li或*t,将参数传入函数里。

def fun(*args):        ###参数前面一定要加*###
    print type(args)
    return max(args),min(args)
li = [1,42,3,14,58,6]
print fun(*li)        ###传递列表时,前面也要加*###

执行结果:
/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/14.py
<type 'tuple'>
(58, 1)

Process finished with exit code 0

###若传递列表时,不加*号###

def fun(*args):
    print type(args)
    return max(args),min(args)
li = [1,42,3,14,58,6]
print fun(li)

执行结果:
/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/14.py
<type 'tuple'>
([1, 42, 3, 14, 58, 6], [1, 42, 3, 14, 58, 6])

Process finished with exit code 0


###传递多个数###

def fun(*args):
    print type(args)
    return max(args),min(args)

print fun(1,42,3,14,58,6)

执行结果:

/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/14.py
<type 'tuple'>
(58, 1)

Process finished with exit code 0




###关键字可变参数###

def enroll(name,age=22,**kwargs):
    print 'name=%s'% name
    print 'age:%d'% age
    for k,w in kwargs.items():
        print '%s:%s'%(k,w)
    print type(kwargs)

enroll('user3',myclass='运维班')

执行结果:
/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/14.py
name=user3
age:22
myclass:运维班
<type 'dict'>

Process finished with exit code 0







参数定义优先级:必选参数>默认参数>可变参数>关键字参数

*arg,可变参数接受的是元组
**kwargs,关键字参数,接受的是字典



###局部变量,只在函数内部生效,全局变量,在整个代码中生效###













本文转自blueclo51CTO博客,原文链接: http://blog.51cto.com/12774272/1947893  ,如需转载请自行联系原作者



相关文章
|
前端开发 测试技术
软件测试|selenium+python基础方法封装(二)
软件测试|selenium+python基础方法封装(二)
154 0
软件测试|selenium+python基础方法封装(二)
|
Web App开发 Java 测试技术
软件测试|selenium+python基础方法封装(一)
软件测试|selenium+python基础方法封装(一)
183 0
软件测试|selenium+python基础方法封装(一)
|
C语言 Python
通过题目入门python基础1
简介:本文通过,python的基础题目,带领大家入门python的基础语法,以实用主义为主。
187 0
通过题目入门python基础1
|
存储 Python
Python基础笔记(持续更新...)
Python基础笔记(持续更新...)
|
数据安全/隐私保护 Python
Python操作ppt和pdf基础
Python操作ppt和pdf基础
290 0
Python操作ppt和pdf基础
|
Python Windows
Python操作word基础
Python操作word基础
181 0
Python操作word基础
|
Python
Python操作excel基础
Python操作excel基础
124 0
Python操作excel基础
|
机器学习/深度学习 存储 人工智能
【paddle领航团基础python课程】三岁水课—结营大作业
【paddle领航团基础python课程】三岁水课—结营大作业
121 0
【paddle领航团基础python课程】三岁水课—结营大作业
|
Python
[Paddle领航团python基础课程大作业一]英文词频的统计任务
[Paddle领航团python基础课程大作业一]英文词频的统计任务
138 0

热门文章

最新文章