Iterate over pairs in a list (circular fashion) in Python
def pairs(lst): i = iter(lst) first = prev = item = i.next() for item in i: yield prev, item prev = item yield item, first Works on any non-empty sequence, no indexing required.
def pairs(lst): i = iter(lst) first = prev = item = i.next() for item in i: yield prev, item prev = item yield item, first Works on any non-empty sequence, no indexing required.
I don’t know about cleaner, but there’s another alternative: for (op, code) in zip(s[0::2], s[1::2]): print op, code A no-copy version: from itertools import izip, islice for (op, code) in izip(islice(s, 0, None, 2), islice(s, 1, None, 2)): print op, code
Start from the top! var elements = [1, 5, 5, 3, 5, 2, 4]; for(var i = elements.length – 1; i >= 0; i–){ if(elements[i] == 5){ elements.splice(i, 1); } }
Beware of properties inherited from the object’s prototype (which could happen if you’re including any libraries on your page, such as older versions of Prototype). You can check for this by using the object’s hasOwnProperty() method. This is generally a good idea when using for…in loops: var user = {}; function setUsers(data) { for (var … Read more
Here’s a way to do it by making use of the way adding one day causes the date to roll over to the next month if necessary, and without messing around with milliseconds. Daylight savings aren’t an issue either. var now = new Date(); var daysOfYear = []; for (var d = new Date(2012, 0, … Read more
Here are some articles you might find of interest Giving STL Iterators a Base Class Type Erasure for C++ Iterators any_iterator Class Reference
The reason the set iteration order changes from run-to-run appears to be because Python uses hash seed randomization by default. (See command option -R.) Thus set iteration is not only arbitrary (because of hashing), but also non-deterministic (because of the random seed). You can override the random seed with a fixed value by setting the … Read more
Guava (formerly Google Collections) has Iterators.concat.
Dart iterables now have a reduce function (https://code.google.com/p/dart/issues/detail?id=1649), so you can do a sum pithily without defining your own fold function: var sum = [1, 2, 3].reduce((a, b) => a + b);
You must dereference the iterator in order to retrieve the member of your set. std::set<unsigned long>::iterator it; for (it = SERVER_IPS.begin(); it != SERVER_IPS.end(); ++it) { u_long f = *it; // Note the “*” here } If you have C++11 features, you can use a range-based for loop: for(auto f : SERVER_IPS) { // use … Read more