Note that there are some explanatory texts on larger screens.

plurals
  1. POEfficient simultaneous update of objects in a list, possibly involving copying. How?
    text
    copied!<p>Suppose I have a list g (In practice a doubly nested list which is three dimensions, but here it's simplified to one dimension for clarity.)</p> <pre><code>g = [1,2,3,2,1] </code></pre> <p>I want a function that can make g[x] = g[x-1]+g[x]. An incorrect way would be</p> <pre><code>def f(thing): for x in xrange(0,len(thing)): thing[x] += thing[x-1] f(g) </code></pre> <p>which is wrong because it updates the integers one-by-one instead of all at once. An alternative is to copy g.</p> <pre><code>gcopy = g[:] def f(thing, copy): for x in xrange(0,len(thing)): thing[x] = copy[x]+copy[x-1] g = gcopy[:] f(g,gcopy) </code></pre> <p>If g has objects, as in my case, <code>copy.deepcopy(g)</code> seems to work. </p> <hr> <p>The issue is that copying becomes my performance bottleneck and deepcopy takes as long to run as the rest of my code combined. </p> <hr> <p>I've searched around on SO and Google for ideas/solutions, and brainstormed a few, but none seemed promising.</p> <p>An answer on this thread: <a href="https://stackoverflow.com/a/16711895/1858363">https://stackoverflow.com/a/16711895/1858363</a>, suggests returning the objects instead of modifying them. I am confused by what that entails though. How does returning the modified objects help?</p> <p>I've heard that copying objects is computationally expensive with deepcopy. If this is true, a possible solution is to replace the objects with lists and store the attributes of the objects as integers and floats in the list. This has the effect of making everything nearly unreadable and might get even more confusing since I have subclasses and inheritance. Since there are only lists, it is then hopefully possible to shallowcopy every list, sublist, subsublist, etc, and reassemble them. Probably not a good solution and it's doubtful the speedup is substantial (though i haven't tested it).</p> <hr> <p>To summarize, is there a way to more efficiently simultaneously change the values of every object in a list with or without copying the list? Or am i stuck with deepcopy? Thank you!</p>
 

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