python3中map函数的使用

以前写的笔记,现在才整理发布出来,以备查询。
Mark一下python中一个好棒的内置函数:map函数。

英文教程参考链接
中文教程参考链接

r= map(func, seq)

参数

  • 第一个参数func 是函数的名称
  • 第二个参数seq是一个序列(比如列表list)

返回值

  • Python 2.x 返回列表。
  • Python 3.x 返回迭代器。(这里的代码都是python3的)

作用: 根据提供的函数对制定序列做映射
直白点说: map()会将func函数应用于序列seq的所有元素

简单例子

  • 函数体

    1
    2
    3
    4
    5
    6
    def fahrenheit(T):
    '''返回华氏温度'''
    return ((float(9)/5)*T + 32)
    def celsius(T):
    '''返回摄氏温度'''
    return (float(5)/9)*(T-32)
  • map使用

    1
    2
    3
    4
    5
    temperatures = (36.5, 37, 37.5, 38, 39)
    F = list(map(fahrenheit, temperatures))
    C = list(map(celsius, F))
    print(F)#[97.7, 98.60000000000001, 99.5, 100.4, 102.2]
    print(C)#[36.5, 37.00000000000001, 37.5, 38.00000000000001, 39.0]

使用lambda匿名函数

1
2
3
C = [39.2, 36.5, 37.3, 38, 37.8] 
F = list(map(lambda x: (float(9)/5)*x + 32, C))
print(F)#[102.56, 97.7, 99.14, 100.4, 100.03999999999999]

可以用于多个列表

  • 列表的元素个数要相同
    1
    2
    print(list(map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])))
    # [3, 7, 11, 15, 19]

应用

因为刚接触python,所以很多内置函数,如果不是真的在打代码中遇到了,可能都记不住。
之所以想mark一下map函数,是在leetcode上刷到一道题: 题目链接

  • 简单翻译一下

    字符串J,代表你拥有的宝石类型。(没有重复的宝石类型)
    字符串S,代表你拥有的石头。
    你想知道这些石头里有多少是宝石。
    字母区分大小写,所以“A”和“a”是不同类型的石头。

  • 例子

    输入: J = “aA”, S = “aAAbbbb”
    输出: 3
    输入: J = “z”, S = “ZZ”
    输出: 0

  • 一开始我的答案是这样纸的

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    class Solution:
    def numJewelsInStones(self, J, S):
    count=0
    jewelsIndex=[]
    for _,jewels in enumerate(J):
    newIndex=[i for i in range(len(S)) if i not in jewelsIndex]
    for i in newIndex:
    if S[i]==jewels:
    count+=1
    jewelsIndex.append(i)
    return count
  • 后来看到大神只用了一句代码

    1
    2
    3
    class Solution:
    def numJewelsInStones(self, J, S):
    return sum(map(J.count, S))
分享到