func = Lambda x = something: x

huangapple go评论56阅读模式
英文:

func = Lambda x = something: x

问题

以下是翻译好的部分:

我在Codewars上做一些练习,找到了这个问题:

> 完成函数scramble(str1, str2),如果可以重新排列str1的一部分字符以匹配str2,则返回true,否则返回false。

在完成它并查看其他答案后,我发现:

scramble=lambda a,b,c=__import__('collections').Counter:not c(b)-c(a)

有人能解释这里发生了什么吗?为什么在lambda声明后有一个=,参数是如何分配的?我没有找到太多解释。

英文:

I was doing some exercises on codewars and found this question:

> Complete the function scramble(str1, str2) that returns true if a portion of str1 characters can be rearranged to match str2, otherwise returns false.

after completing it and looking at others answers I found:

scramble=lambda a,b,c=__import__('collections').Counter:not c(b)-c(a)

Can someone explain what is happening here? Why is there a = after the declaration of lambda and how are the arguments being assigned???

I did not found much explanation on this.

答案1

得分: 6

等号用于为c参数设置默认值。默认值是__import__('collections').Counter

Lambda表达式等价于:

def scramble(a, b, c=__import__('collections').Counter):
    return not c(b) - c(a)

或者,去掉import语句:

import collections
def scramble(a, b, c=collections.Counter):
    return not c(b) - c(a)

不同之处在于,__import__不会将导入的模块赋给collections变量。

英文:

The equal sign is setting a default value for the c argument. The default value is __import__('collections').Counter.

The lambda is equivalent to

def scramble(a, b, c=__import__('collections').Counter):
    return not c(b)-c(a)

or, extracting the import,

import collections
def scramble(a, b, c=collections.Counter):
    return not c(b)-c(a)

except that __import__ doesn't assign the imported module to the collections variable.

huangapple
  • 本文由 发表于 2023年5月17日 11:19:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76268353.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定