英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论