Number of lines in csv.DictReader
rows = list(myreader) totalrows = len(rows) for i, row in enumerate(rows): print(“Row %d/%d” % (i+1, totalrows))
rows = list(myreader) totalrows = len(rows) for i, row in enumerate(rows): print(“Row %d/%d” % (i+1, totalrows))
Your suspicion is correct: the iterator has been consumed. In actuality, your iterator is a generator, which is an object which has the ability to be iterated through only once. type((i for i in range(5))) # says it’s type generator def another_generator(): yield 1 # the yield expression makes it a generator, not a function … Read more
The difference is in terms of efficiency. For example, many languages other than PHP include two range functions, range() and xrange(). This is a really good example of generators and why to use them. Let’s build our own: function range($start, $end) { $array = array(); for ($i = $start; $i <= $end; $i++) { $array[] … Read more
Nowadays you can simply use the spread operator with its Rest way: const { key, …profilesWithoutKey } = profiles; Credit to this blog post
I prefer the for loop because it also sets the scope of the iterator to just the for loop.
As far as I understand, you want want the iterator to return a vector of references into itself, right? Unfortunately, it is not possible in Rust. This is the trimmed down Iterator trait: trait Iterator { type Item; fn next(&mut self) -> Option<Item>; } Note that there is no lifetime connection between &mut self and … Read more
Iterate through keys & values: for (var k:Object in dictionary) { var value:ValType = dictionary[k]; var key:KeyType = k; } Iterate through values more concisely: for each (var value:ValType in dictionary) { }
Presumably because the Collection interface was introduced in Java 1.2 whereas Iterable appeared only in 1.5, and changing the interface would break all existing implementations.
from itertools import islice def split_every(n, iterable): i = iter(iterable) piece = list(islice(i, n)) while piece: yield piece piece = list(islice(i, n)) Some tests: >>> list(split_every(5, range(9))) [[0, 1, 2, 3, 4], [5, 6, 7, 8]] >>> list(split_every(3, (x**2 for x in range(20)))) [[0, 1, 4], [9, 16, 25], [36, 49, 64], [81, 100, 121], … Read more
First of all, Way 2 and Way 3 are identical in practically all standard library implementations. Apart from that, the options you posted are almost equivalent. The only notable difference is that in Way 1 and Way 2/3, you rely on the compiler to optimize the call to v.end() and v.size() out. If that assumption … Read more