python学习日记:day16-------内置函数与匿名函数

栏目: Python · 发布时间: 6年前

内容简介:python学习日记:day16-------内置函数与匿名函数

一、内置函数

1,数据类型:int,bool ..........

2,数据结构:dict,list,tuple,set,str

3,reversed--保留原列表,返回一个反序的迭代器

reversed()
l =[1,2,3,4,5]
l2 =reversed(l)
print(l2)

4,slice切片 

l =(1,2,23,213,5612,234,43)
sli =slice(1,5,2)
print(l[sli])

#(2,213)

5,format

print(format('test', '<20'))
print(format('test', '>40'))
print(format('test', '^40'))

6,bytes

#bytes 转换成bytes类型
# 我拿到的是gbk编码的,我想转成utf-8编码
# print(bytes('你好',encoding='GBK'))     # unicode转换成GBK的bytes
# print(bytes('你好',encoding='utf-8'))   # unicode转换成utf-8的bytes
7,bytearray
b_array = bytearray('你好',encoding='utf-8')
print(b_array)
print(b_array[0])
7,zip 
l = [1,2,3,4,5]
l2 = ['a','b','c','d']
l3 = ('*','**',[1,2])
d = {'k1':1,'k2':2}
for i in zip(l,l2,l3,d):
    print(i)

8,all

只有有一个为false则返回false

9,any

只要有一个为True则为True

10,filter

执行了filter之后的结果集合一定是《= 执行之前的个数

#filter只管筛选,不会改变原来的值

11,map

#执行前后元素的个数不变,值可能发生改

12,sorted

#用 c语言 编写。

数据少、短、且要保留原来的列表

二、匿名函数

def add(x,y):
    return x+y

转换成匿名函数为:

add = lambda x,y:x+y
print(add(1,2))

1,找出value值最大的key

dic={'k1':10,'k2':100,'k3':30}
def func(key):
    return dic[key]
print(max(dic,key=func))   #根据返回值判断最大值,返回值最大的那个参数是结果
print(max(dic,key=lambda key:dic[key]))
max([1,2,3,4,5,-6,-7],key=abs)

2,说出代码的最终结果

d = lambda p:p*2
t = lambda p:p*3
x = 2
x = d(x) #x = 4
x = t(x) #x = 12
x = d(x) #x = 24
print(x)
#--->24

3、

#现有两元组(('a'),('b')),(('c'),('d')),
# 请使用 python 中匿名函数生成列表[{'a':'c'},{'b':'d'}]
ret = zip((('a'),('b')),(('c'),('d')))
ret = map(lambda t:{t[0]:t[1]},ret)
print(list(ret))
4,以下代码的输出是什么?请给出答案并解释。
def multipliers():
    return [lambda x:i*x for i in range(4)]
print([m(2) for m in multipliers()])
请修改multipliers的定义来产生期望的结果。
def multipliers():
    return (lambda x:i*x for i in range(4))#改为生成器
print([m(2) for m in multipliers()])

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Master Switch

The Master Switch

Tim Wu / Knopf / 2010-11-2 / USD 27.95

In this age of an open Internet, it is easy to forget that every American information industry, beginning with the telephone, has eventually been taken captive by some ruthless monopoly or cartel. Wit......一起来看看 《The Master Switch》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具