简体   繁体   中英

python key=lambda understanding and c# equivalent

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 ac# equivalent or comparable to python's min ?

Thanks in advance.

  1. Yes. In particular, hulls[i][j] could be any type or any value depending on what happened at runtime. eg 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 eg min('a','b') is 'a'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM