【问题标题】:Understand the map function in Python - Index reassignment理解 Python 中的 map 函数——索引重新分配
【发布时间】:2013-12-17 18:25:56
【问题描述】:

我试图了解 map 函数如何在 Python 中使用这种用法: 我有

def permutate(table, block):
"""Permutate this block with the specified table"""
    return(map(lambda x: block[x], table))

ls_bits =    [0,1,0,0,1,1,1,0]
IP =         [2,3,1,4,7,0]

ls_bits= permutate (IP, ls_bits)
print (list(ls_bits))


>>> 
[0, 0, 1, 1, 0, 0]

它完全符合我的要求:它获取ls_bits (ls_bits[i]) 中的i 索引的值,并将该值重新分配给ls_bits 中的IP[i] 值索引。比如ls_bits[1] = 1IP[1] = 3,那么在map函数之后,ls_bits[3] = 1

但我不明白为什么(我在网上找到了这个方法),因为我没有使用“地图方法”中的任何功能

提前感谢您的帮助,我希望我足够清楚,您可以理解我的问题

【问题讨论】:

    标签: python map indexing


    【解决方案1】:

    lambda 表达式作为函数传递给map。它被定义为一个嵌套函数,以便能够引用另一个函数参数block。来自docs

    可以使用 lambda 关键字创建小型匿名函数。此函数返回其两个参数的总和:lambda a, b: a+b。 Lambda 函数可用于需要函数对象的任何地方。它们在语法上仅限于单个表达式。从语义上讲,它们只是普通函数定义的语法糖。与嵌套函数定义一样,lambda 函数可以引用包含范围内的变量 [...]

    函数map() 用于将可调用(第一个参数)顺序应用到可迭代(第二个参数)。它为返回的可迭代对象中包含的每个元素构建可调用的返回值列表。

    总之,它是

    的简写
    def permutate(table, block):
        """Permutate this block with the specified table"""
        def index(x):
            return block[x]
        ret = []
        for x in table:
            ret.append(index(x))
        return ret
    

    供参考:

    【讨论】:

      【解决方案2】:

      map 将函数 lambda x: block[x] 应用于可迭代 table 的每个元素并返回结果数组

      【讨论】:

        【解决方案3】:
        def permutate(IP, bits):
            return(map(lambda x: bits[x], IP))
            # To apply lambda function on IP list
            # x is any elem of IP list
            # return the index of elems in the IP list
        
            # bits[2] ---> 0. becuase index of 2 in the IP list is zero.
            # bits[3] ---> 0. becuase index of 3 in the IP list is zero.
            # bits[1] ---> 1. becuase index of 1 in the IP list is one.
            # bits[4] ---> 1. becuase index of 4 in the IP list is one.
            # bits[7] ---> 0. becuase index of 7 in the IP list is zero.
            # bits[0] ---> 0. becuase index of 0 in the IP list is zero.
        
            ### Visualization ###
            # elems of bits          --> 0   1   0   0   1   1   1   0
            # index of elems of btis --> 0   1   2   3   4   5   6   7
        
        bits = [0,1,0,0,1,1,1,0]
        IP   = [2,3,1,4,7,0]
        
        print ('indexes of IP list :', list(permutate(IP, bits)))
        

        【讨论】:

        • 你看看上面的程序就行了。
        猜你喜欢
        • 2022-11-22
        • 2020-04-22
        • 2016-11-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-03
        • 1970-01-01
        • 2014-01-30
        相关资源
        最近更新 更多