473,624 Members | 2,165 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

groupby

can some explain why in the 2nd example, m doesn't print the list [1, 1, 1]
which i had expected?

for k, g in groupby([1, 1, 1, 2, 2, 3]): .... print k, list(g)
....
1 [1, 1, 1]
2 [2, 2]
3 [3]

m = list(groupby([1, 1, 1, 2, 2, 3]))
m [(1, <itertools._gro uper object at 0x00AAC600>), (2, <itertools._gro uper object
at 0x00AAC5A0>), (3, <itertools._gro uper object at 0x00AAC5B0>)] list(m[0][1]) []

thanks,

bryan

May 23 '06 #1
4 2289
Bryan wrote:
can some explain why in the 2nd example, m doesn't print the list [1, 1, 1]
which i had expected?

>>> for k, g in groupby([1, 1, 1, 2, 2, 3]): ... print k, list(g)
...
1 [1, 1, 1]
2 [2, 2]
3 [3]

>>> m = list(groupby([1, 1, 1, 2, 2, 3]))
>>> m [(1, <itertools._gro uper object at 0x00AAC600>), (2, <itertools._gro uper object
at 0x00AAC5A0>), (3, <itertools._gro uper object at 0x00AAC5B0>)] >>> list(m[0][1]) [] >>>

thanks,

bryan


I've tripped on this more than once, but it's in the docs
(http://docs.python.org/lib/itertools-functions.html):

"The returned group is itself an iterator that shares the underlying
iterable with groupby(). Because the source is shared, when the groupby
object is advanced, the previous group is no longer visible. So, if
that data is needed later, it should be stored as a list"

George

May 23 '06 #2
George Sakkis wrote:
Bryan wrote:
can some explain why in the 2nd example, m doesn't print the list [1, 1, 1]
which i had expected?

>>> for k, g in groupby([1, 1, 1, 2, 2, 3]):

... print k, list(g)
...
1 [1, 1, 1]
2 [2, 2]
3 [3]

>>> m = list(groupby([1, 1, 1, 2, 2, 3]))
>>> m

[(1, <itertools._gro uper object at 0x00AAC600>), (2, <itertools._gro uper object
at 0x00AAC5A0>), (3, <itertools._gro uper object at 0x00AAC5B0>)]
>>> list(m[0][1])

[]
>>>

thanks,

bryan


I've tripped on this more than once, but it's in the docs
(http://docs.python.org/lib/itertools-functions.html):

"The returned group is itself an iterator that shares the underlying
iterable with groupby(). Because the source is shared, when the groupby
object is advanced, the previous group is no longer visible. So, if
that data is needed later, it should be stored as a list"

George


i read that description in the docs so many times before i posted here. now that
i read it about 10 more times, i finally get it. there's just something about
the wording that kept tripping me up, but i can't explain why :)

thanks,

bryan

May 23 '06 #3
"Bryan" <be****@gmail.c om> wrote in message
news:ma******** *************** *************** *@python.org...
George Sakkis wrote: <snip>
"The returned group is itself an iterator that shares the underlying
iterable with groupby(). Because the source is shared, when the groupby
object is advanced, the previous group is no longer visible. So, if
that data is needed later, it should be stored as a list"

George


i read that description in the docs so many times before i posted here.

now that i read it about 10 more times, i finally get it. there's just something about the wording that kept tripping me up, but i can't explain why :)

thanks,

bryan


So here's how to save the values from the iterators while iterating over the
groupby:
m = [(x,list(y)) for x,y in groupby([1, 1, 1, 2, 2, 3])]
m

[(1, [1, 1, 1]), (2, [2, 2]), (3, [3])]

-- Paul
May 23 '06 #4
"Paul McGuire" <pt***@austin.r r._bogus_.com> wrote in message
news:bz******** **********@torn ado.texas.rr.co m...
So here's how to save the values from the iterators while iterating over the groupby:
m = [(x,list(y)) for x,y in groupby([1, 1, 1, 2, 2, 3])]
m

[(1, [1, 1, 1]), (2, [2, 2]), (3, [3])]

-- Paul


Playing some more with groupby. Here's a one-liner to tally a list of
integers into a histogram:

# create data set, random selection of numbers from 1-10
dataValueRange = range(1,11)
data = [random.choice(d ataValueRange) for i in xrange(10)]
print data

# tally values into histogram:
# (from the inside out:
# - sort data into ascending order, so groupby will see all like values
together
# - call groupby, return iterator of (value,valueIte mIterator) tuples
# - tally groupby results into a dict of (value, valueFrequency) tuples
# - expand dict into histogram list, filling in zeroes for any keys that
didn't get a value
hist = [ (k1,dict((k,len (list(g))) for k,g in
itertools.group by(sorted(data) )).get(k1,0)) for k1 in dataValueRange ]

print hist

Gives:
[9, 6, 8, 3, 2, 3, 10, 7, 6, 2]
[(1, 0), (2, 2), (3, 2), (4, 0), (5, 0), (6, 2), (7, 1), (8, 1), (9, 1),
(10, 1)]

Change the generation of the original data list to 10,000 values, and you
get something like:
[(1, 995), (2, 986), (3, 941), (4, 998), (5, 978), (6, 1007), (7, 997), (8,
1033), (9, 1038), (10, 1027)]

If you know there wont be any zero frequency values (or don't care about
them), you can skip the fill-in-the-zeros step, with one of these
expressions:
histAsList = [ (k,len(list(g)) ) for k,g in itertools.group by(sorted(data) ) ]
histAsDict = dict((k,len(lis t(g))) for k,g in
itertools.group by(sorted(data) ))

-- Paul
May 27 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1405
by: G?nter Jantzen | last post by:
In the documentation http://www.python.org/dev/doc/devel/whatsnew/node7.html is written about itertools.groupby: """Like it SQL counterpart, groupby() is typically used with sorted input.""" In SQL queries is the groupby clause not related to 'input order'. This notion makes not much sense in SQL context. SQL is based on relational Algebra. A SQL- table is based on an
3
1703
by: trebucket | last post by:
What am I doing wrong here? >>> import operator >>> import itertools >>> vals = .... (1, 16), (2, 17), (3, 18), (4, 19), (5, 20)] >>> for k, g in itertools.groupby(iter(vals), operator.itemgetter(0)): .... print k, .... 1
20
1900
by: Frank Millman | last post by:
Hi all This is probably old hat to most of you, but for me it was a revelation, so I thought I would share it in case someone has a similar requirement. I had to convert an old program that does a traditional pass through a sorted data file, breaking on a change of certain fields, processing each row, accumulating various totals, and doing additional processing at each break. I am not using a database for this one, as the file
1
6753
by: Roman Bertle | last post by:
Hello, there is an example how to use groupby in the itertools documentation (http://docs.python.org/lib/itertools-example.html): # Show a dictionary sorted and grouped by value .... print k, map(itemgetter(0), g) .... 1 2
13
4566
by: 7stud | last post by:
Bejeezus. The description of groupby in the docs is a poster child for why the docs need user comments. Can someone explain to me in what sense the name 'uniquekeys' is used this example: import itertools mylist = def isString(x):
3
1474
by: Steve Howell | last post by:
George Sakkis produced the following cookbook recipe, which addresses a common problem that comes up on this mailing list: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/521877 I would propose adding something like this to the cookbook example above.
10
1616
by: 7stud | last post by:
I'm applying groupby() in a very simplistic way to split up some data, but when I timeit against another method, it takes twice as long. The following groupby() code groups the data between the "</tr>" strings: data = import itertools def key(s): if s == "<":
9
2991
by: patrick.waldo | last post by:
Hi all, I tried reading http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/334695 on the same subject, but it didn't work for me. I'm trying to learn how to make pivot tables from some excel sheets and I am trying to abstract this into a simple sort of example. Essentially I want to take input data like this: Name Time of day Amount Bob Morn 240
3
9237
by: Wiktor Zychla [C# MVP] | last post by:
could someone enlighten me on what would be the difference between GroupBy and ToLookup? I try hard but am not able to spot any difference between these two. the syntax and behavioral semantics is the same. is there any explanation on why we need them both? Thanks in advance, Wiktor Zychla
0
8234
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8172
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8677
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8620
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8335
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7158
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4174
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2605
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1784
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.