IMPORTANT NOTE: You have to sort your data first.
The part I didn't get is that in the example construction
groups = []
uniquekeys = []
for k, g in groupby(data, keyfunc):
groups.append(list(g)) # Store group iterator as a list
uniquekeys.append(k)
k
is the current grouping key, and g
is an iterator that you can use to iterate over the group defined by that grouping key. In other words, the groupby
iterator itself returns iterators.
Here's an example of that, using clearer variable names:
from itertools import groupby
things = [("animal", "bear"), ("animal", "duck"), ("plant", "cactus"), ("vehicle", "speed boat"), ("vehicle", "school bus")]
for key, group in groupby(things, lambda x: x[0]):
for thing in group:
print("A %s is a %s." % (thing[1], key))
print("")
This will give you the output:
A bear is a animal.
A duck is a animal.
A cactus is a plant.
A speed boat is a vehicle.
A school bus is a vehicle.
In this example, things
is a list of tuples where the first item in each tuple is the group the second item belongs to.
The groupby()
function takes two arguments: (1) the data to group and (2) the function to group it with.
Here, lambda x: x[0]
tells groupby()
to use the first item in each tuple as the grouping key.
In the above for
statement, groupby
returns three (key, group iterator) pairs - once for each unique key. You can use the returned iterator to iterate over each individual item in that group.
Here's a slightly different example with the same data, using a list comprehension:
for key, group in groupby(things, lambda x: x[0]):
listOfThings = " and ".join([thing[1] for thing in group])
print(key + "s: " + listOfThings + ".")
This will give you the output:
animals: bear and duck.
plants: cactus.
vehicles: speed boat and school bus.
Here's a generator that yields the chunks you want:
def chunks(lst, n):
"""Yield successive n-sized chunks from lst."""
for i in range(0, len(lst), n):
yield lst[i:i + n]
import pprint
pprint.pprint(list(chunks(range(10, 75), 10)))
[[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
[30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
[40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
[50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
[60, 61, 62, 63, 64, 65, 66, 67, 68, 69],
[70, 71, 72, 73, 74]]
If you're using Python 2, you should use xrange()
instead of range()
:
def chunks(lst, n):
"""Yield successive n-sized chunks from lst."""
for i in xrange(0, len(lst), n):
yield lst[i:i + n]
Also you can simply use list comprehension instead of writing a function, though it's a good idea to encapsulate operations like this in named functions so that your code is easier to understand. Python 3:
[lst[i:i + n] for i in range(0, len(lst), n)]
Python 2 version:
[lst[i:i + n] for i in xrange(0, len(lst), n)]
Best Answer
It's pretty simple really:
There is also the
step
value, which can be used with any of the above:The key point to remember is that the
:stop
value represents the first value that is not in the selected slice. So, the difference betweenstop
andstart
is the number of elements selected (ifstep
is 1, the default).The other feature is that
start
orstop
may be a negative number, which means it counts from the end of the array instead of the beginning. So:Similarly,
step
may be a negative number:Python is kind to the programmer if there are fewer items than you ask for. For example, if you ask for
a[:-2]
anda
only contains one element, you get an empty list instead of an error. Sometimes you would prefer the error, so you have to be aware that this may happen.Relation to
slice()
objectThe slicing operator
[]
is actually being used in the above code with aslice()
object using the:
notation (which is only valid within[]
), i.e.:is equivalent to:
Slice objects also behave slightly differently depending on the number of arguments, similarly to
range()
, i.e. bothslice(stop)
andslice(start, stop[, step])
are supported. To skip specifying a given argument, one might useNone
, so that e.g.a[start:]
is equivalent toa[slice(start, None)]
ora[::-1]
is equivalent toa[slice(None, None, -1)]
.While the
:
-based notation is very helpful for simple slicing, the explicit use ofslice()
objects simplifies the programmatic generation of slicing.