python基础8
程序员文章站
2024-03-26 10:02:05
...
高阶函数
map
参数:map(func,*iterables)
第一个参数是函数,必须要有形参,接受序列中的元素。按照函数对数据进行改变之后的结果。
第二个参数是要进行转化的序列。
res = map(str,list0)
ret = map(lambda x,y:(y,x),'abcdef',[123456]
res = list(map(str,list0)
传统方法:
newlist = []
list0 = [1,3,6,9,4]
for ele in list0:
new_list.append(str(ele))
print(new_list)
eg:
#不借助int eval 将字符串0-9转为整型
1、def ch_int(ch):
ch_dict = {"0":0,"1":1,"2":2,"3":3,"4":4,"5","6":6,"7":7,"8":8,"9":9}
return ch_dict[ch]
res = list(map(ch_int,["0","2","4"]))
return res
print(res)
2、from functools import reduce
s = '25452'
DIGITS = {'0': 0,'1': 1,'2': 2,'3': 3,'4': 4,'5': 5,'6': 6,'7': 7,'8': 8,'9': 9}
def str2int(s):
def fn(x, y):
return x * 10 + y
def char2num(s):
return DIGITS[s]
return reduce(fn, map(char2num, s))
根据设计的序列格式,对多个序列进行重组
1、res = dict(map(lambda x,y:(x,y),"abcdef",[1,2,3,4,5,6]))
print(res)
组成字典的两种方式:
#交换字典键和值的方式
1、dict0 = {"a":97,"b":98}
new_dict = {}
for k,v in dict0.items():
new_dict[v] = k
print(new_dict)
2、res = dict(map(lambda k,v:(v,k),dict0.keys(),dict0.values()))
print(res)
3、ret = {v:k for k,v for k,v in dict0.items()}
print(ret)
4、ret = dict(zip(dict0.values(),dict0.keys()))
print(ret)
# 将列表中整型数据转为字符串类型
1、newlist = []
list0 = [1,3,6,9,4]
for ele in list0:
new_list.append(str(ele))
print(new_list)
2、def ch_int(ch):
ch_dict = {"0":0,"1":1,"2":2,"3":3,"4":4,"5","6":6,"7":7,"8":8,"9":9}
return ch_dict[ch]
res = list(map(ch_int,["0","1","2","3","4","5","6","7","8","9"]))
return res
print(res)
reduce
redcuce(func,iterable)
func 接受一个参数 第一次接受的序列中的前两个元素
不借助int,eval求两个字符串中数据的和
form funtools import reduce
def ch_Int(ch):
ch_int = {"0":0, "1":1, "2":2, "3":3, "4":4, "5":5, "6":6, "7":7, "8":8, "9":9}
return ch_int[ch]
map_obj = map(ch_int,s)
res = reduce(lambda x,y:x*10 +y,map_obj)
result = reduce(lambda x,y:x*10 + y,map_obj)
num1 = input('')
num2 = input(' ')
res = ch_int(num1) + ch_int(num2)
print(res)
从二次开始接受下一个元素,以及上一次两个元素的运算结果。
filter
filter(func,iterable)
设置函数,必须有形参和返回值
res = list(filter(lambda ele:type(ele)==str,list0)
筛选年龄小于50的
dict_list = [{"name":"老王","age":58},{"name":"老张","age":48},{"name":"小王","age":38},{"name":"小张","age":68}]
res = list(filter(lambda ele:ele["age"]<=50,dict_list))
print(res)
#去掉字符串中的数字
s = "cac546svas46416acs6ac6sa"
1、news_s = ''
for ch in new_s:
if not ch.isdigit():
new_s += ch
print(new_s)
2、res = "".join(filter(lambda ch:not ch.isdigit(),s))
print(res)
#保留成绩>=60的键值对
dict0 = {"语文":77, "数学":54, "英语":88, "历史":42}
1、 new_dict = {}
for k,v in dict0.items():
if v >= 60:
new_dict[k] = v
print(new_dict)
2、res = dict(filter(lambda item:item[1]>=60,dict0.items()))
print(res)
sorted
sorted(排序的列表,key = 函数,reverse = True,False)
会生成一个新的列表对原列表无影响。
list0 = [12,36,85,56,41,21]
new_list = sorted(list0,key = lambda ele:-ele,reverse = True)
zip
zip(序列,序列) 进行重组时,以长度较短的序列为标准。