python基础3-12764272
python基础3交换:
a,b=b,a
相当于定义了一个元组t=(b,a)
然后将t的值给了a,t的值给了b
####字典####
定义用花括号
集合定义若为空的话,会默认为字典,所以集合不能为空
子典只能通过关键字来查找值,因为字典是key-value(关键字-值),因此不能通过值来查找关键字
In : dic = {"user1":"123","user2":"234","user3":"789"}
In : dic["234"]
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-3-2845b64d96b1> in <module>()
----> 1 dic["234"]
KeyError: '234'
字典是一个无序的数据类型,因此也不能进行索引和切片等操作。
In : dic = {"user1":"123","user2":"234","user3":"789"}
In : dic["user1"]
Out: '123'
In : dic["user2"]
Out: '234'
In : user = ['user1','user2','user3']
In : passwd = ['123','234','456']
In : zip(user,passwd)
Out: [('user1', '123'), ('user2', '234'), ('user3', '456')]
In :
当你有一个用户名单和密码,若使用列表的类型,判断用户是否和密码一致时,就比较麻烦,而使用字典时,只需通过关键子就可以返回相对应的值,(如上例子:当定义一个子典当你搜索user1时,字典类型就会返回该关键字对应的密码,此时只需判断该密码是否匹配即可)
####字典的基本操作###
In : dic.
dic.clear dic.items dic.pop dic.viewitems
dic.copy dic.iteritems dic.popitem dic.viewkeys
dic.fromkeys dic.iterkeys dic.setdefaultdic.viewvalues
dic.get dic.itervaluesdic.update
dic.has_key dic.keys dic.values
字典添加
In : dic
Out: {'user1': '123', 'user2': '234', 'user3': '789'}
In : dic["westos"]='linux'
In : dic
Out: {'user1': '123', 'user2': '234', 'user3': '789', 'westos': 'linux'}
In : dic["hello"]='world'
In : dic ####由此可以看出字典是无序的,在添加时,并不会按照顺序往后添加####
Out:
{'hello': 'world',
'user1': '123',
'user2': '234',
'user3': '789',
'westos': 'linux'}
In :
字典更新
In : dic
Out: {'hello': 'world', 'user1': '123', 'user2': '234', 'user3': '789'}
In : dic["user1"]="redhat" ###可直接通过赋值对关键字进行更新###
In : dic
Out: {'hello': 'world', 'user1': 'redhat', 'user2': '234', 'user3': '789'}
###或者通过dic.update更新###
In : dic
Out: {'hello': 'world', 'user1': 'redhat', 'user2': '234', 'user3': '789'}
In : help(dic.update)
Help on built-in function update:
update(...)
D.update(**F) -> None.Update D from dict/iterable E and F.
If E present and has a .keys() method, does: for k in E: D = E
If E present and lacks .keys() method, does: for (k, v) in E: D = v
In either case, this is followed by: for k in F: D = F
(END)
In : dic1={'yunwei':"westos",'user1': 'redhat'}
In : dic.update(dic)
dic dic1dict
In : dic.update(dic1) ###将dic1中dic所没有的更新给了dic###
In : dic
Out:
{'hello': 'world',
'user1': 'redhat',
'user2': '234',
'user3': '789',
'yunwei': 'westos'}
In :
####若是关键字相同,而值不同,就将值更新给他####
In : dic
Out: {'hello': 'world'}
In : dic1
Out: {'user1': 'redhat', 'yunwei': 'westos'}
In : dic1["hello"]="hai"
In : dic.update(dic1)
In : dic
Out: {'hello': 'hai', 'user1': 'redhat', 'yunwei': 'westos'}
In : dic.clear() ###清空dic###
In : dic
Out: {}
In : del(dic) ###删除dic###
In : dic
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-45-1b445b6ea935> in <module>()
----> 1 dic
NameError: name 'dic' is not defined
####字典的删除####
In : dic1
Out: {'user1': 'redhat', 'yunwei': 'westos'}
In : dic1.pop("user1") ###指定关键字,删除该关键字和值####
Out: 'redhat'
In : dic1
Out: {'yunwei': 'westos'}
In :
In : dic1.popitem() ###不指定关键字,随即删除###
Out: ('yunwei', 'westos')
In : dic = {"hello":"123","westos":"linux"}
In : dic.keys() ###查看dic的全部关键字###
Out: ['hello', 'westos']
In : dic.values() ###查看dic的全部值###
Out: ['123', 'linux']
In : dic.get("hello") ###得到相对应的关键字的值,若关键字不存在,则默认返回none
Out: '123'
In : dic.get("redhat")
In : print dic.get("redhat")
None
In : dic.has_key("hello") ###查看是否有该关键字,
Out: True
In : dic.has_key("world")
Out: False
dict.fromkeys() ###可以通过该操作实现去重###
In : dic
Out: {'hello': '123', 'westos': 'linux'}
In : dic.fromkeys()
Out: {1: None, 2: None, 3: None, 4: None}
In : dic.fromkeys(,'hello')
Out: {1: 'hello', 2: 'hello', 3: 'hello', 4: 'hello'}
In : d = {}
In : li = ###去重###
In : d.fromkeys(li)
Out: {1: None, 2: None, 3: None}
In : d.fromkeys(li).keys()
Out:
字典的key必须是不可变的数据类型
In : dic = {1:'1',2:'2',1:'a'}
In : dic
Out: {1: 'a', 2: '2'} ###一个关键字只能对应一个值###
In : for key in dic.keys(): ###逐个遍历key###
....: print "key=%s" % key
....:
key=1
key=2
In : for value in dic.values(): ###逐个遍历value的值###
print "value=%s" % value
....:
value=a
value=2
In : for key,value in dic.keys(),dic.values(): ###逐个遍历key -> value 的值#####
....: print "%s -> %s" %(key,value)
....:
1 -> 2
a -> 2
In : dic
Out: {1: 'a', 2: '2'}
In : dic.items() ###以元组的形式一一对应key和value的值###
Out: [(1, 'a'), (2, '2')]
In : for k,v in dic.items():
.....: print "%s -> %s" %(k,v)
.....:
1 -> a
2 -> 2
和list的比较,dict的不同:
1 查找和插入的速度快,字典不会随着key值的增加查找速度减慢
2 占用内存大,浪费空间
小练习:
去掉一个最高分和最低分,并且显示平均值
li =
In : li =
In : li.sort() ###排序###
In : li
Out:
In : li.pop()
Out: 100
In : li.pop(0)
Out: 67
In : li
Out:
In : sum(li)/len(li) ###sum函数求和###
Out: 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
#####函数####
函数名的理解:函数名与变量名类似,其实就是指向一个函数对象的引用;
给这个函数起了一个“别名”:函数名赋给一个变量
In : sum(li)
Out: 6
In : a = sum ###将sum的函数名给了a变量,使得a能够进行求和###
In : a(li)
Out: 6
In :
In : sum = abs
In : sum(-1)
Out: 1
In : sum( ###将abs的函数名给了sum,则sum就不再具有求和的功能###
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-10-d3c81a94a2a0> in <module>()
----> 1 sum()
TypeError: bad operand type for abs(): 'list'
In : a()
Out: 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()
print fun()
print fun()
执行结果:
/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/14.py
['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()
print fun()
print fun()
执行结果为:
/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/14.py
['END']
['END']
Process finished with exit code 0
####可变参数###
定义参数时,形参可以为*args,使函数可与接受多个参数;
如果想要将一个列表或者元组传入参数,也可以通过*li或*t,将参数传入函数里。
def fun(*args): ###参数前面一定要加*###
print type(args)
return max(args),min(args)
li =
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 =
print fun(li)
执行结果:
/usr/bin/python2.7 /home/kiosk/PycharmProjects/pythonbasic/14.py
<type 'tuple'>
(, )
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,关键字参数,接受的是字典
###局部变量,只在函数内部生效,全局变量,在整个代码中生效###
页:
[1]