Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>See the example in the Python documentation for <code>bisect</code>:</p> <blockquote> <p>Unlike the sorted() function, it does not make sense for the bisect() functions to have key or reversed arguments because that would lead to an inefficient design (successive calls to bisect functions would not “remember” all of the previous key lookups).</p> <p>Instead, it is better to search a list of precomputed keys to find the index of the record in question:</p> </blockquote> <pre><code>&gt;&gt;&gt; data = [('red', 5), ('blue', 1), ('yellow', 8), ('black', 0)] &gt;&gt;&gt; data.sort(key=lambda r: r[1]) &gt;&gt;&gt; keys = [r[1] for r in data] # precomputed list of keys &gt;&gt;&gt; data[bisect_left(keys, 0)] ('black', 0) &gt;&gt;&gt; data[bisect_left(keys, 1)] ('blue', 1) &gt;&gt;&gt; data[bisect_left(keys, 5)] ('red', 5) &gt;&gt;&gt; data[bisect_left(keys, 8)] ('yellow', 8) </code></pre> <p>So in your case:</p> <pre><code>nested_list = [[123,'Aaron','CA'],[124,'Bob','WY'],[125,'John','TX']] insert_me = [122,'George','AL'] keys = [r[1] for r in nested_list] nested_list.insert(bisect.bisect_left(keys,insert_me[1]),insert_me) [[123, 'Aaron', 'CA'], [124, 'Bob', 'WY'], [122, 'George', 'AL'], [125, 'John', 'TX']] </code></pre> <p>To avoid rebuilding the <code>keys</code> everytime, insert new values into <code>keys</code> as well:</p> <pre><code>keys.insert(bisect_left(keys,insert_me[1]),insert_me[1]) </code></pre> <hr> <p>Update:</p> <p>Did some performance comparison between insert/bisect, append/sorted and heapq solutions:</p> <pre><code># elements heapq insert/bisect append/sorted 10,000 0.01s 0.08s 2.43s 20,000 0.03s 0.28s 10.06s 30,000 0.04s 0.60s 22.81s </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