我试图了解 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
索引值,并重新分配该值value 到 ls_bits
中值 IP[i]
的索引。例如,ls_bits[1] = 1
、IP[1] = 3
,因此在map函数之后,ls_bits[3] = 1
.
但我不明白为什么(我在网上找到了这个方法),因为我没有使用“ map 方法”中的任何函数
预先感谢您的帮助,我希望我足够清楚,让您能够理解我的问题
最佳答案
lambda 表达式 作为函数传递给 map
。它被定义为一个嵌套函数,以便能够引用其他函数参数block
。来自 docs :
Small anonymous functions can be created with the lambda keyword. This function returns the sum of its two arguments:
lambda a, b: a+b
. Lambda functions can be used wherever function objects are required. They are syntactically restricted to a single expression. Semantically, they are just syntactic sugar for a normal function definition. Like nested function definitions, lambda functions can reference variables from the containing scope [...]
函数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
供引用:
关于python - 了解Python中的map函数——索引重新分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20641880/