python key=lambda 理解和 C# 等效

发布于 2024-12-13 20:13:15 字数 1043 浏览 3 评论 0原文

我自己记录了有关“key=lambda”功能的信息,并找到了有关其使用的很好的参考:

http://www.daniweb.com/software-development/python/threads/376964

感谢它,我开始了解以下代码“应该”做什么:

def _min_hull_pt_pair(hulls):
    """Returns the hull, point index pair that is minimal."""
    h, p = 0, 0
    for i in xrange(len(hulls)):
        j = min(xrange(len(hulls[i])), key=lambda j: hulls[i][j])
        if hulls[i][j] < hulls[h][p]:
            h, p = i, j
    return (h, p)   

但是我有一个以下语法的问题:

        j = min(xrange(len(hulls[i])), key=lambda j: hulls[i][j])

我的疑问,作为一个Python学徒,尽管学得很快:

1-我是否需要像调用堆栈一样回溯以了解我检索的“类型”或更简单的“值”[我][j]? (我读到 python 使用“鸭子打字”,如果我没记错的话,这可以解释这种需求)。

2- key=lambda j 基本上“检索”了 hulls 的 [i][j] 元素,不是吗?但这是否意味着 hulls[i][j] 是整数类型,因为“for”迭代使用 for 的 xrange 调用“min”?

3-可选:是否有 c# 与 python 的 min 等效或相当?

提前致谢。

I have documented myself regarding the 'key=lambda' functionality, and have found a good reference on its use:

http://www.daniweb.com/software-development/python/threads/376964

thanks to which I came to understand what the following code is 'supposed' to do:

def _min_hull_pt_pair(hulls):
    """Returns the hull, point index pair that is minimal."""
    h, p = 0, 0
    for i in xrange(len(hulls)):
        j = min(xrange(len(hulls[i])), key=lambda j: hulls[i][j])
        if hulls[i][j] < hulls[h][p]:
            h, p = i, j
    return (h, p)   

however I have a problem with the following syntax:

        j = min(xrange(len(hulls[i])), key=lambda j: hulls[i][j])

My doubts, being a python apprentice albeit learning fast:

1- do I need to trace back the calls stack-like to understand what 'type' or more simply 'value' I get retrieving hulls[i][j]? (I read that python uses the 'duck typing', which would explain this need, if I'm not mistaken).

2- key=lambda j basically 'retrieves' the [i][j] element of hulls, doesn't it? But does this mean that hulls[i][j] is an integer type, since the 'for' iteration calls 'min' with the for's xrange?

3- optional: is there a c# equivalent or comparable to python's min?

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

等风来 2024-12-20 20:13:15
  1. 是的。特别是,hulls[i][j] 可以是任何类型或任何值,具体取决于运行时发生的情况。例如,所有 hulls 都可以是整数,但您可以设置 hulls[i][j]='foo'

  2. 是的,那里的 lambda 返回 hulls 中第 i 行的第 j 个元素。 hulls[i][j] 可以是任何类似的东西,例如 min('a','b') is 'a'

  1. Yes. In particular, hulls[i][j] could be any type or any value depending on what happened at runtime. e.g. all of hulls could be integers, but you can set hulls[i][j]='foo'.

  2. Yes, the lambda there returns the jth element of the ith row in hulls. hulls[i][j] could be any comparable thing e.g. min('a','b') is 'a'

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文