了解Python中的映射函数-索引重新分配
我正试图了解映射函数在Python中如何使用这种用法: 我有 它做的正是我想要的:它获取了解Python中的映射函数-索引重新分配,python,map,indexing,Python,Map,Indexing,我正试图了解映射函数在Python中如何使用这种用法: 我有 它做的正是我想要的:它获取ls\u位中I索引的值(ls\u位[I]),并将该值重新分配到ls\u位中的IP[I]索引。例如,ls\u位[1]=1,IP[1]=3,因此在map函数之后,ls\u位[3]=1 但是我不明白为什么(我在网上找到了这个方法),因为我没有在“map方法”中使用任何函数 提前感谢您的帮助,我希望我已经足够清楚,您可以理解我的问题lambda表达式作为函数传递给map。它被定义为一个嵌套函数,能够引用其他函数参数块
ls\u位中I
索引的值(ls\u位[I]
),并将该值重新分配到ls\u位中的IP[I]
索引。例如,ls\u位[1]=1
,IP[1]=3
,因此在map函数之后,ls\u位[3]=1
但是我不明白为什么(我在网上找到了这个方法),因为我没有在“map方法”中使用任何函数
提前感谢您的帮助,我希望我已经足够清楚,您可以理解我的问题lambda表达式作为函数传递给map
。它被定义为一个嵌套函数,能够引用其他函数参数块
。从:
可以使用lambda关键字创建小型匿名函数。此函数返回其两个参数之和:lambda,b:a+b
。Lambda函数可以在需要函数对象的任何地方使用。它们在语法上仅限于一个表达式。在语义上,它们只是普通函数定义的语法糖。与嵌套函数定义一样,lambda函数可以引用包含范围[…]中的变量
函数map()
用于将可调用(第一个参数)顺序应用于可调用(第二个参数)。它为iterable in return中包含的每个元素构建一个可调用的返回值列表
总而言之,这是一个缩写
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
供参考:
map
将函数lambda x:block[x]
应用于iterable表的每个元素
,并返回一个结果数组您只需查看上述程序即可。
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)))
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)))