Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <pre><code>In [6]: sorted(mydict.iteritems(), key=lambda (k,v): operator.itemgetter(1)(v)) Out[6]: [('a2', ['e', 2]), ('a4', ['s', 2]), ('a3', ['h', 3]), ('a1', ['g', 6]), ('a6', ['y', 7]), ('a5', ['j', 9])] </code></pre> <p>The key parameter is always a function that is fed one item from the iterable (<code>mydict.iteritems()</code>) at a time. In this case, an item could be something like </p> <pre><code>('a2',['e',2]) </code></pre> <p>So we need a function that can take <code>('a2',['e',2])</code> as input and return 2.</p> <p><code>lambda (k,v): ...</code> is an anonymous function which takes one argument -- a 2-tuple -- and unpacks it into <code>k</code> and <code>v</code>. So when the <code>lambda</code> function is applied to our item, <code>k</code> would be <code>'a2'</code> and <code>v</code> would be <code>['e',2]</code>. </p> <p><code>lambda (k,v): operator.itemgetter(1)(v)</code> applied to our item thus returns <code>operator.itemgetter(1)(['e',2])</code>, which "itemgets" the second item in <code>['e',2]</code>, which is 2.</p> <p>Note that <code>lambda (k,v): operator.itemgetter(1)(v)</code> is not a good way to code in Python. As gnibbler points out, <code>operator.itemgetter(1)</code> is recomputed <em>for each item</em>. That's inefficient. The point of using <code>operator.itemgetter(1)</code> is to create a function that can be applied many times. You don't want to re-create the function each time. <code>lambda (k,v): v[1]</code> is more readable, and faster:</p> <pre><code>In [15]: %timeit sorted(mydict.iteritems(), key=lambda (k,v): v[1]) 100000 loops, best of 3: 7.55 us per loop In [16]: %timeit sorted(mydict.iteritems(), key=lambda (k,v): operator.itemgetter(1)(v)) 100000 loops, best of 3: 11.2 us per loop </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload