2.5 map、filter、reduce、sorted 函数

from collections import Iterator
lt = [1, 2, 3, 4, 5]


def pingfang(x):
    return x * x


# 返回一个迭代器
ret = map(pingfang, lt)
# ret = map(lambda x: 2 * x, lt)

print(isinstance(ret, Iterator))    # True
print(list(ret))                    #[1, 4, 9, 16, 25]


s = '   hello  '
# 删除两边的特定字符,不指定时删除空白字符
# s = s.strip('AB')
# 删除右边的
# s = s.rstrip()
# 删除左边的
s = s.lstrip()
print('AAA'+s+'AAA')                #  AAAhello  AAA




lt = [1, 2, 3, 4, 5]


def oushu(x):
    return x%2 == 0
# f = filter(oushu, lt)
f = filter(lambda x: x%2 != 0, lt)  #  [1, 3, 5]
print(list(f))




lt = [1, 2, 3, 4, 5]


def add(a, b):
    return a + b


# ret = reduce(add, lt)
# 转换为12345
ret = reduce(lambda x, y: x * 10 + y, lt)  #12345
print(ret)





lt = [1, 3, 5, 7, 2, 4, 6]

# 排序函数
lt2 = sorted(lt, reverse=True)

print(lt)    #   [1, 3, 5, 7, 2, 4, 6]
print(lt2)   #   [7, 6, 5, 4, 3, 2, 1]

猜你喜欢

转载自blog.csdn.net/XC_LMH/article/details/81414780