python的常用函数

目录

1.map、reduce、filter

2.zip

1.map、reduce、filter

from functools import reduce

#  map
def f(x):
    return x * x
r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print(map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9]))  # <map object at 0x0000018AD46D84E0>
print(r)  # <map object at 0x0000018AD46D84A8>
print(list(r))  # [1, 4, 9, 16, 25, 36, 49, 64, 81]


# reduce
def fn(x, y):
    return x * 10 + y
def char2num(s):
    digits = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
    return digits[s]
r = map(char2num, '13579')
print(map(char2num, '13579'))  # <map object at 0x0000018AD46D84A8>
print(r)  # <map object at 0x0000018AD46D81D0>
print(list(r))  # [1, 3, 5, 7, 9]
print(reduce(fn, map(char2num, '13579')))  # 13579
print(reduce(fn, [1, 3, 5, 7, 9]))  # 13579


#filter
def is_odd(n):
    return n % 2 == 1
print(list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])))  # 结果: [1, 5, 9, 15]
def not_empty(s):
    return s and s.strip()
print(list(filter(not_empty, ['A', '', 'B', None, 'C', '  '])))  # 结果: ['A', 'B', 'C']

2.zip

# zip
a = [1, 2, 3]
b = [4, 5, 6]
c = [4, 5, 6, 7, 8]
zipped = zip(a, b)   # [(1, 4), (2, 5), (3, 6)], 打包为元组的列表
zip(a, c)  # [(1, 4), (2, 5), (3, 6)], 元素个数与最短的列表一致
zip(*zipped)  # [(1, 2, 3), (4, 5, 6)],与 zip 相反,*zipped 可理解为解压,返回二维矩阵式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值