Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>For the first question, the first thing you should do is sort the list by the second field using <a href="https://docs.python.org/3/library/operator.html#operator.itemgetter" rel="nofollow noreferrer">itemgetter</a> from the operator module:</p> <pre><code>x = [ ['4', '21', '1', '14', '2008-10-24 15:42:58'], ['3', '22', '4', '2somename', '2008-10-24 15:22:03'], ['5', '21', '3', '19', '2008-10-24 15:45:45'], ['6', '21', '1', '1somename', '2008-10-24 15:45:49'], ['7', '22', '3', '2somename', '2008-10-24 15:45:51'] ] from operator import itemgetter x.sort(key=itemgetter(1)) </code></pre> <p>Then you can use itertools' <a href="https://docs.python.org/3/library/itertools.html#itertools.groupby" rel="nofollow noreferrer">groupby</a> function:</p> <pre><code>from itertools import groupby y = groupby(x, itemgetter(1)) </code></pre> <p>Now y is an iterator containing tuples of (element, item iterator). It's more confusing to explain these tuples than it is to show code:</p> <pre><code>for elt, items in groupby(x, itemgetter(1)): print(elt, items) for i in items: print(i) </code></pre> <p>Which prints:</p> <pre><code>21 &lt;itertools._grouper object at 0x511a0&gt; ['4', '21', '1', '14', '2008-10-24 15:42:58'] ['5', '21', '3', '19', '2008-10-24 15:45:45'] ['6', '21', '1', '1somename', '2008-10-24 15:45:49'] 22 &lt;itertools._grouper object at 0x51170&gt; ['3', '22', '4', '2somename', '2008-10-24 15:22:03'] ['7', '22', '3', '2somename', '2008-10-24 15:45:51'] </code></pre> <p>For the second part, you should use list comprehensions as mentioned already here:</p> <pre><code>from pprint import pprint as pp pp([y for y in x if y[3] == '2somename']) </code></pre> <p>Which prints:</p> <pre><code>[['3', '22', '4', '2somename', '2008-10-24 15:22:03'], ['7', '22', '3', '2somename', '2008-10-24 15:45:51']] </code></pre>
    singulars
    1. This table or related slice is empty.
    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