python - 了解Python中的map函数——索引重新分配

标签 python dictionary indexing

我试图了解 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] = 1IP[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/

相关文章:

python - 绘制条形图 - ValueError : The truth value of a DataFrame is ambiguous. 使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()

python - 从 numpy 图像中提取彩色线

java - Java 中基于字典的搜索优化

c# - 如何通过 .NET 在 MongoDB 中创建索引

python - 在 python 代码和 c++ 代码 (IPC) 之间共享信息

python - 初始化对象变量——一种 Java 方法,一种 Python 方法?

python - 字典变量如何存储在内存中?

python - 如何遍历 python 字典列表

sql-server - SQL Server 不会使用我的索引

mysql在两列之间选择太慢