key函数python key函数是什么意思( 四 )


printu'keys方法:'
list=d.keys()
printlist
printu'\niterkeys方法:'
it=d.iterkeys()
forxinit:
printx
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three':3,'two':2,'one':1}
keys方法:
['three','two','one']
iterkeys方法:
three
two
one
3.8 pop函数:删除字典中对应的键
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
printd
d.pop('one')
printd
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three':3,'two':2,'one':1}
{'three':3,'two':2}
3.9 popitem函数:移出字典中的项
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
printd
d.popitem()
printd
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three':3,'two':2,'one':1}
{'two':2,'one':1}
3.10 setdefault函数:类似于get方法,获取与给定键相关联的值,也可以在字典中不包含给定键的情况下设定相应的键值
# _*_ coding:utf-8 _*_
d={'one':1,'two':2,'three':3}
printd
printd.setdefault('one',1)
printd.setdefault('four',4)
printd
运算结果:
{'three':3,'two':2,'one':1}
{'four':4,'three':3,'two':2,'one':1}
3.11 update函数:用一个字典更新另外一个字典
# _*_ coding:utf-8 _*_
d={
'one':123,
'two':2,
'three':3
}
printd
x={'one':1}
d.update(x)
printd
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
{'three':3,'two':2,'one':123}
{'three':3,'two':2,'one':1}
3.12 values和itervalues函数:values以列表的形式返回字典中的值 , itervalues返回值得迭代器,由于在字典中值不是唯一的,所以列表中可以包含重复的元素
# _*_ coding:utf-8 _*_
d={
'one':123,
'two':2,
'three':3,
'test':2
}
printd.values()
运算结果:
=======RESTART: C:\Users\Mr_Deng\Desktop\test.py=======
[2,3,2,123]
Python基础之常见内建函数map() 函数接受两个参数,一个是函数,一个是可迭代对象(Iterable), map 将传入的函数依次作用到可迭代对象的每一个元素,并把结果作为迭代器(Iterator)返回 。
举例说明,有一个函数 f(x)=x^2,要把这个函数作用到一个list [1,2,3,4,5,6,7,8,9] 上:
运用简单的循环可以实现:
运用高阶函数 map() :
结果 r 是一个迭代器,迭代器是惰性序列,通过 list() 函数让它把整个序列都计算出来并返回一个 list。
如果要把这个list所有数字转为字符串利用 map() 就简单了:
小练习:利用 map() 函数,把用户输入的不规范的英文名字变为首字母大写其他小写的规范名字 。输入 ['adam', 'LISA', 'barT'] ,输出 ['Adam', 'Lisa', 'Bart']
reduce() 函数也是接受两个参数,一个是函数 , 一个是可迭代对象,reduce 将传入的函数作用到可迭代对象的每个元素的结果做累计计算 。然后将最终结果返回 。
效果就是: reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
举例说明,将序列 [1,2,3,4,5] 变换成整数 12345 :
小练习:编写一个 prod() 函数,可以接受一个 list 并利用 reduce 求积:
map() 和 reduce() 综合练习:编写 str2float 函数,把字符串 '123.456' 转换成浮点型 123.456
filter() 函数用于过滤序列, filter() 也接受一个函数和一个序列,filter() 把传入的函数依次作用于每个元素,然后根据返回值是 True 还是 False 决定保留还是丢弃该元素 。
举例说明,删除list中的偶数:

推荐阅读