Discuss / Python / map/reduce函数,欢迎交流

map/reduce函数,欢迎交流

Topic source

草莓Z葵

#1 Created at ... [Delete] [Delete and Lock User]

#练习1

def normalize(name):

    return name[0].upper() + name[1:].lower()

草莓Z葵

#2 Created at ... [Delete] [Delete and Lock User]

#练习2

def prod(L):

    def ji(x, y):

        return x * y

    return reduce(ji, L)

草莓Z葵

#3 Created at ... [Delete] [Delete and Lock User]

#练习3

"""

解决思路1(参考 “游泳的旱鸭子” ):

1. 字符串以"."切片组合成新的字符串ls

2. 使用字典DICT{}和Fs()函数做str到int的转换

3. 使用reduce()和num()将int转换成整数

4. 以s[f+1:]做小数点的左移

"""

def str2float(s):

    f = s.index(".")

    ls = s[:f] + s[f+1:]

    DICT = {"0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9}

    def Fs(s):

        return DICT[s]

    def num(x, y):

        return x * 10 + y

    return reduce(num, map(Fs, ls)) * 0.1 ** len(s[f+1:])

草莓Z葵

#4 Created at ... [Delete] [Delete and Lock User]

#联系3

"""

解决思路2:

1. 字符串以"."切片组合成新的列表n,n[0]代表整数位,n[1]代表小数位

2. FS()引用字典DICT做str到int的转换

3. reduce()和char2num()将int转换成整数

4. list(map(Fs, n[0])) + list(map(Fs, n[1]))作用是组合成一个列表用于reduce()运算

5. 0.1 ** len(n[1])确认小数点有多少位

"""

def str2float(s):

    n = s.split(".")

    DICT = {"0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9}

    def Fs(s):

        return DICT[s]

    def char2num(x, y):

        return x * 10 + y

    return reduce(char2num, list(map(Fs, n[0])) + list(map(Fs, n[1]))) * 0.1 ** len(n[1])

草莓Z葵

#5 Created at ... [Delete] [Delete and Lock User]

重在思考的过程(纠结了一天),更加省事的方式是float(s)一步到位)逃


  • 1

Reply