Thursday, April 1, 2010

comp.lang.python - 25 new messages in 10 topics - digest

comp.lang.python
http://groups.google.com/group/comp.lang.python?hl=en

comp.lang.python@googlegroups.com

Today's topics:

* sorting ascending/descending with operator.attrgetter - 2 messages, 2
authors
http://groups.google.com/group/comp.lang.python/t/95c91eb2efe1bcc7?hl=en
* Getting a Python program to run of off a flash drive? - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/dfae8f896caac5da?hl=en
* String Formatting Operations for decimals. - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.python/t/71c71012403f0187?hl=en
* Python + OpenOffice Calc - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/22165c0d3711582a?hl=en
* Q: We have *args and **kwargs. Woud ***allargs be useful? - 1 messages, 1
author
http://groups.google.com/group/comp.lang.python/t/c6aed08acf3bc006?hl=en
* Developement Question? - 2 messages, 2 authors
http://groups.google.com/group/comp.lang.python/t/44ac4387b21d6c29?hl=en
* newbie with a encoding question, please help - 8 messages, 3 authors
http://groups.google.com/group/comp.lang.python/t/dbf7a1880d0bb2a0?hl=en
* associative array - 4 messages, 4 authors
http://groups.google.com/group/comp.lang.python/t/2cba5368a4df0374?hl=en
* decorators only when __debug__ == True - 3 messages, 3 authors
http://groups.google.com/group/comp.lang.python/t/5da23b4a51e9a19e?hl=en
* Python 3.1, object, and setattr() - 1 messages, 1 author
http://groups.google.com/group/comp.lang.python/t/621c86af4d407a34?hl=en

==============================================================================
TOPIC: sorting ascending/descending with operator.attrgetter
http://groups.google.com/group/comp.lang.python/t/95c91eb2efe1bcc7?hl=en
==============================================================================

== 1 of 2 ==
Date: Wed, Mar 31 2010 11:54 pm
From: Steven D'Aprano


On Wed, 31 Mar 2010 21:54:40 -0700, Patrick Maupin wrote:

> There is a (not very subtle) difference between saying "Oh, you meant a
> list, not a string" (especially when the context was a discussion of
> list processing), and printing a traceback for something that nobody was
> discussing, based on a single word slip.

I wondered about that.

I almost asked whether or not you would have reacted with less anger if I
hadn't included the tracebacks, but decided against it. I thought that,
given how you dropped a nuke on me for what was a very trivial social
faux pas, you would probably interpret a question about the tracebacks as
me being condescending and go on the attack yet again.

So far you've dropped a ton of sarcasm on me for being "the smartest,
sharpest guy in the world", accused me of "deliberately
misinterpret[ing] everything [you] write", and declared that my work-
mates (who you don't know) take great pleasure in putting me down. Such
repeated attacks, over something as trivial as me pointing out you
mistook list.sort for str.sort puts your comment:

"I've left less poisonous workplaces for less cause."

into a completely different perspective. How little a slight does it take
for you to decide a workplace is poisonous?

So, Patrick, here's how it goes:

I won't apologize for pointing out your error, no matter how trivial,
because I thought, and still do, that it muddied the waters and risked
adding confusion rather than clarity to somebody asking a very basic
question. And for all I knew, you may have been genuinely confused
yourself, and not just making a silly typo.

I will say that I regret including the tracebacks, not because there is
anything wrong with doing so, but because they apparently caused you
distress and I had no intention to do so. I am sorry that you took
offense, it was not intended.

At the risk of offending you further, I will suggest that I'm not the
only one who needs to apply some introspection here. If your skin is so
thin that you react so explosively to such a minor slight, how are you
going to react to some of the more vigorous disagreements?

--
Steven


== 2 of 2 ==
Date: Thurs, Apr 1 2010 7:00 am
From: Patrick Maupin


On Apr 1, 1:54 am, Steven D'Aprano
<ste...@REMOVE.THIS.cybersource.com.au> wrote:
> At the risk of offending you further, I will suggest that I'm not the
> only one who needs to apply some introspection here. If your skin is so
> thin that you react so explosively to such a minor slight, how are you
> going to react to some of the more vigorous disagreements?

I think, if you go back and read other threads, you will find that a)
I react fine to even very vigorous technical disagreements, and b) my
reaction to you in particular (which, yes, introspection does show
that I need to not react right away) is because of an induced
sensitivity. Perhaps I'll see my allergist.

Regards,
Pat

==============================================================================
TOPIC: Getting a Python program to run of off a flash drive?
http://groups.google.com/group/comp.lang.python/t/dfae8f896caac5da?hl=en
==============================================================================

== 1 of 1 ==
Date: Thurs, Apr 1 2010 1:22 am
From: timo verbeek


On Apr 1, 12:48 am, Abethebabe <abrahamalra...@gmail.com> wrote:
> I wanted to know if there was a way I could get a Python program to
> run off of my flash drive as soon as the computer (Windows) detected
> the device?
>
> For example I could have a a simple program that would create a text
> document on the computers desktop when my flash drive is detected.

You could use Autorun.inf if your using Windows but for linux I don't
now

==============================================================================
TOPIC: String Formatting Operations for decimals.
http://groups.google.com/group/comp.lang.python/t/71c71012403f0187?hl=en
==============================================================================

== 1 of 2 ==
Date: Thurs, Apr 1 2010 2:08 am
From: Lacrima


Hello!

I need to format a decimal (floating point) number in the following
way:
10 results in '10'
10.5 results in '10.5'
10.50 results in '10.5'
10.5678 results in 10.57

How can I achieve this using standard Python string formatting
operations?
Something like '%.2f' works almost as expected:
>>> '%.2f' % 10.5
'10.50'
>>> '%.2f' % 10.5678
'10.57'
>>> '%.2f' % 10
'10.00'
But I always need trailing zeros to be excluded, i.e. 10.5 should
result in '10.5' (not '10.50'), and 10 should result in '10' (not
'10.00').
So how can I do this?
Sorry for my English.
Thanks in advance.

with regards,
Maxim


== 2 of 2 ==
Date: Thurs, Apr 1 2010 2:14 am
From: Chris Rebert


On Thu, Apr 1, 2010 at 2:08 AM, Lacrima <lacrima.maxim@gmail.com> wrote:
> Hello!
>
> I need to format a decimal (floating point) number in the following
> way:
> 10 results in '10'
> 10.5 results in '10.5'
> 10.50 results in '10.5'
> 10.5678 results in 10.57
>
> How can I achieve this using standard Python string formatting
> operations?
> Something like '%.2f' works almost as expected:
>>>> '%.2f' % 10.5
> '10.50'
>>>> '%.2f' % 10.5678
> '10.57'
>>>> '%.2f' % 10
> '10.00'
> But I always need trailing zeros to be excluded, i.e. 10.5 should
> result in '10.5' (not '10.50'), and 10 should result in '10' (not
> '10.00').
> So how can I do this?

('%.2f' % 10).rstrip('0').rstrip('.')

Cheers,
Chris
--
http://blog.rebertia.com

==============================================================================
TOPIC: Python + OpenOffice Calc
http://groups.google.com/group/comp.lang.python/t/22165c0d3711582a?hl=en
==============================================================================

== 1 of 1 ==
Date: Thurs, Apr 1 2010 2:38 am
From: "eglyph@gmail.com"


On Apr 1, 6:53 am, rantingrick <rantingr...@gmail.com> wrote:

> > 3 fields: quantity - description of the piece bought - price
>
> So what is your plan...?
>   * Pop up a dialog with three entrys,
>   * have him fill out the three entrys,
>   * then have python insert the data into the spreadsheet?
> ...Why bother messing with OO, too much trouble for me?

Totally agree with you. No need for a heavy machinery in this case.

> Then just save all the data as csv and you
> can always load it into a spreadsheet later if the IRS comes knocking,
> or you need to print a professional looking spreadsheet ;-).  Simple,
> 100% python solution!

Actually, a spreadsheet based solution isn't best fit for such a task.
I'd recommend to store the data in sqlite3 (also 100% pure python as
the module is in the stdlib). CSV is good for making invoices or
something like that.

==============================================================================
TOPIC: Q: We have *args and **kwargs. Woud ***allargs be useful?
http://groups.google.com/group/comp.lang.python/t/c6aed08acf3bc006?hl=en
==============================================================================

== 1 of 1 ==
Date: Thurs, Apr 1 2010 2:57 am
From: Jonathan Fine


The idioms
def f(*args, **kwargs):
# Do something.
and
args = (1, 2, 3)
kwargs = dict(a=4, b=5)
g(*args, **kwargs)
are often useful in Python.

I'm finding myself picking up /all/ the arguments and storing them for
later use (as part of a testing framework). So for me it would be nice
if I could write
def f(***allargs):
args, kwargs = allargs
# Continue as before.

However, if we do this then 'args' in '*args' is misleading. So I'll
use 'sargs' (for sequence arguments) instead.

I can now write, for a suitable class Args
args = Args(1, 2, 3, a=4, b=5)
g(***args) # Same as before.
sargs, kwargs = args
g(*sargs, **kwargs) # Same as before.

Even better, now that Args is a class we can give it a method 'call' so that
args.call(g)
is equivalent to
g(***args)
which removes the need for the *** construct.

This reminds me of functools.partial except, of course, we've fixed all
the arguments and left the passing of the function for later, whereas in
partial we fix the function and some of the arguments.
http://docs.python.org/library/functools.html#functools.partial

My view are that
1. Conceptually ***allargs is useful, but an Args class would be more
useful (not that it need be either-or).

2. If Args were built in , there could be performance benefits.

3. It's clearer to write
def(*seqargs, **kwargs):
than
def(*args, **kwargs):

4. When the Args class is used a lot, one might welcome
def(***args):
# Do something with args.
as a shortcut (and minor speedup) for
def(*seqargs, **kwargs):
args = Args(*seqargs, **kwargs)
# Do something with args.

I look forward to your comments on this.

--
Jonathan

==============================================================================
TOPIC: Developement Question?
http://groups.google.com/group/comp.lang.python/t/44ac4387b21d6c29?hl=en
==============================================================================

== 1 of 2 ==
Date: Thurs, Apr 1 2010 3:34 am
From: Wayne


My town office uses Microsoft operating system. They have a proprietary
accounting system that uses excel for their accounting reports.
I would like to read these report and reproduce the report so that
the report can be seen on the web. I was thinking about using xlrd and
xlwt along with some sort of software for building the web pages. I
use linux only and do not use Microsoft.
Q. Does python have to be installed on there computer to run the script?

Q. Am I approaching this the wrong way? If so, what would be a better
approach?


== 2 of 2 ==
Date: Thurs, Apr 1 2010 5:58 am
From: MRAB


Wayne wrote:
> My town office uses Microsoft operating system. They have a proprietary
> accounting system that uses excel for their accounting reports.
> I would like to read these report and reproduce the report so that
> the report can be seen on the web. I was thinking about using xlrd and
> xlwt along with some sort of software for building the web pages. I
> use linux only and do not use Microsoft.
> Q. Does python have to be installed on there computer to run the script?
>
If you can copy the spreadsheet files to your machine then you can run the
script on your machine.

> Q. Am I approaching this the wrong way? If so, what would be a better
> approach?
>


==============================================================================
TOPIC: newbie with a encoding question, please help
http://groups.google.com/group/comp.lang.python/t/dbf7a1880d0bb2a0?hl=en
==============================================================================

== 1 of 8 ==
Date: Thurs, Apr 1 2010 3:56 am
From: Mister Yu


hi experts,

i m new to python, i m writing crawlers to extract data from some
chinese websites, and i run into a encoding problem.

i have a unicode object, which looks like this u'\xd6\xd0\xce\xc4'
which is encoded in "gb2312", but i have no idea of how to convert it
back to utf-8

to re-create this one is easy:

this will work
============================
>>> su = u"中文".encode('gb2312')
>>> su
u
>>> print su.decode('gb2312')
中文 -> (same as the original string)

============================
but this doesn't,why
===========================
>>> su = u'\xd6\xd0\xce\xc4'
>>> su
u'\xd6\xd0\xce\xc4'
>>> print su.decode('gb2312')
Traceback (most recent call last):
File "<console>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position
0-3: ordinal not in range(128)
===========================

thank you


== 2 of 8 ==
Date: Thurs, Apr 1 2010 4:22 am
From: Chris Rebert


2010/4/1 Mister Yu <eryan.yu@gmail.com>:
> hi experts,
>
> i m new to python, i m writing crawlers to extract data from some
> chinese websites, and i run into a encoding problem.
>
> i have a unicode object, which looks like this u'\xd6\xd0\xce\xc4'
> which is encoded in "gb2312",

No! Instances of type 'unicode' (i.e. strings with a leading 'u')
***aren't encoded at all***.

> but i have no idea of how to convert it
> back to utf-8

To convert u'\xd6\xd0\xce\xc4' to UTF-8, do u'\xd6\xd0\xce\xc4'.encode('utf-8')

> to re-create this one is easy:
>
> this will work
> ============================
>>>> su = u"中文".encode('gb2312')
>>>> su
> u
>>>> print su.decode('gb2312')
> 中文    -> (same as the original string)
>
> ============================
> but this doesn't,why
> ===========================
>>>> su = u'\xd6\xd0\xce\xc4'
>>>> su
> u'\xd6\xd0\xce\xc4'
>>>> print su.decode('gb2312')
You can't decode a unicode string, it's already been decoded!

One decodes a bytestring to get a unicode string.
One **encodes** a unicode string to get a bytestring.

So the last line of your example should be:
print su.encode('gb2312')

Only call .encode() on things of type 'unicode'.
Only call .decode() on things of type 'str'.
[When using Python 2.x that is. Python 3.x renames the types in question.]

Cheers,
Chris
--
http://blog.rebertia.com


== 3 of 8 ==
Date: Thurs, Apr 1 2010 4:38 am
From: Mister Yu


On Apr 1, 7:22 pm, Chris Rebert <c...@rebertia.com> wrote:
> 2010/4/1 Mister Yu <eryan...@gmail.com>:
>
> > hi experts,
>
> > i m new to python, i m writing crawlers to extract data from some
> > chinese websites, and i run into a encoding problem.
>
> > i have a unicode object, which looks like this u'\xd6\xd0\xce\xc4'
> > which is encoded in "gb2312",
>
> No! Instances of type 'unicode' (i.e. strings with a leading 'u')
> ***aren't encoded at all***.
>
> > but i have no idea of how to convert it
> > back to utf-8
>
> To convert u'\xd6\xd0\xce\xc4' to UTF-8, do u'\xd6\xd0\xce\xc4'.encode('utf-8')
>
>
>
> > to re-create this one is easy:
>
> > this will work
> > ============================
> >>>> su = u"中文".encode('gb2312')
> >>>> su
> > u
> >>>> print su.decode('gb2312')
> > 中文    -> (same as the original string)
>
> > ============================
> > but this doesn't,why
> > ===========================
> >>>> su = u'\xd6\xd0\xce\xc4'
> >>>> su
> > u'\xd6\xd0\xce\xc4'
> >>>> print su.decode('gb2312')
>
> You can't decode a unicode string, it's already been decoded!
>
> One decodes a bytestring to get a unicode string.
> One **encodes** a unicode string to get a bytestring.
>
> So the last line of your example should be:
> print su.encode('gb2312')
>
> Only call .encode() on things of type 'unicode'.
> Only call .decode() on things of type 'str'.
> [When using Python 2.x that is. Python 3.x renames the types in question.]
>
> Cheers,
> Chris
> --http://blog.rebertia.com

hi, thanks for the tips.

but i m still not very sure how to convert a unicode object **
u'\xd6\xd0\xce\xc4 ** back to "中文" the string it supposed to be?

thanks.

sorry i m really new to python.


== 4 of 8 ==
Date: Thurs, Apr 1 2010 4:47 am
From: Mister Yu


===========================================
print u'\xd6\xd0\xce\xc4'.encode('utf-8')
ÖÐÎÄ (the result is supposed to be "中文" but not something like
this)
===========================================

>>> su = u"中文".encode('gb2312')
>>> su
'\xd6\xd0\xce\xc4'
===========================================

== 5 of 8 ==
Date: Thurs, Apr 1 2010 5:13 am
From: Chris Rebert


On Thu, Apr 1, 2010 at 4:38 AM, Mister Yu <eryan.yu@gmail.com> wrote:
> On Apr 1, 7:22 pm, Chris Rebert <c...@rebertia.com> wrote:
>> 2010/4/1 Mister Yu <eryan...@gmail.com>:
>> > hi experts,
>>
>> > i m new to python, i m writing crawlers to extract data from some
>> > chinese websites, and i run into a encoding problem.
>>
>> > i have a unicode object, which looks like this u'\xd6\xd0\xce\xc4'
>> > which is encoded in "gb2312",
<snip>
> hi, thanks for the tips.
>
> but i m still not very sure how to convert a unicode object  **
> u'\xd6\xd0\xce\xc4 ** back to "中文" the string it supposed to be?

Ah, my apologies! I overlooked something (sorry, it's early in the
morning where I am).
What you have there is ***really*** screwy. It's the 2 Chinese
characters, encoded in gb2312, and then somehow cast *directly* into a
'unicode' string (which ought never to be done).

In answer to your original question (after some experimentation):
gb2312_bytes = ''.join([chr(ord(c)) for c in u'\xd6\xd0\xce\xc4'])
unicode_string = gb2312_bytes.decode('gb2312')
utf8_bytes = unicode_string.encode('utf-8') #as you wanted

If possible, I'd look at the code that's giving you that funky
"string" in the first place and see if it can be fixed to give you
either a proper bytestring or proper unicode string rather than the
bastardized mess you're currently having to deal with.

Apologies again and Cheers,
Chris
--
http://blog.rebertia.com


== 6 of 8 ==
Date: Thurs, Apr 1 2010 5:16 am
From: Stefan Behnel


Mister Yu, 01.04.2010 13:38:
> i m still not very sure how to convert a unicode object **
> u'\xd6\xd0\xce\xc4 ** back to "中文" the string it supposed to be?

You are confused. '\xd6\xd0\xce\xc4' is an encoded byte string, not a
unicode string. The fact that you have it stored in a unicode string
implies that something in your code (or in a library) has done an incorrect
conversion from bytes to unicode that did not take into account the real
character set in use. So you end up with a completely meaningless unicode
string.

Please show us the code that does the conversion to a unicode string.

Stefan

== 7 of 8 ==
Date: Thurs, Apr 1 2010 5:26 am
From: Mister Yu


On Apr 1, 8:13 pm, Chris Rebert <c...@rebertia.com> wrote:
> On Thu, Apr 1, 2010 at 4:38 AM, Mister Yu <eryan...@gmail.com> wrote:
> > On Apr 1, 7:22 pm, Chris Rebert <c...@rebertia.com> wrote:
> >> 2010/4/1 Mister Yu <eryan...@gmail.com>:
> >> > hi experts,
>
> >> > i m new to python, i m writing crawlers to extract data from some
> >> > chinese websites, and i run into a encoding problem.
>
> >> > i have a unicode object, which looks like this u'\xd6\xd0\xce\xc4'
> >> > which is encoded in "gb2312",
> <snip>
> > hi, thanks for the tips.
>
> > but i m still not very sure how to convert a unicode object  **
> > u'\xd6\xd0\xce\xc4 ** back to "中文" the string it supposed to be?
>
> Ah, my apologies! I overlooked something (sorry, it's early in the
> morning where I am).
> What you have there is ***really*** screwy. It's the 2 Chinese
> characters, encoded in gb2312, and then somehow cast *directly* into a
> 'unicode' string (which ought never to be done).
>
> In answer to your original question (after some experimentation):
> gb2312_bytes = ''.join([chr(ord(c)) for c in u'\xd6\xd0\xce\xc4'])
> unicode_string = gb2312_bytes.decode('gb2312')
> utf8_bytes = unicode_string.encode('utf-8') #as you wanted
>
> If possible, I'd look at the code that's giving you that funky
> "string" in the first place and see if it can be fixed to give you
> either a proper bytestring or proper unicode string rather than the
> bastardized mess you're currently having to deal with.
>
> Apologies again and Cheers,
> Chris
> --http://blog.rebertia.com

Hi Chris,

thanks for the great tips! it works like a charm.

i m using the Scrapy project(http://doc.scrapy.org/intro/
tutorial.html
) to write my crawler, when it extract data with xpath,
it puts the chinese characters directly into the unicode object.

thanks again chris, and have a good april fool day.

Cheers,
Yu


== 8 of 8 ==
Date: Thurs, Apr 1 2010 6:31 am
From: Stefan Behnel


Mister Yu, 01.04.2010 14:26:
> On Apr 1, 8:13 pm, Chris Rebert wrote:
>> gb2312_bytes = ''.join([chr(ord(c)) for c in u'\xd6\xd0\xce\xc4'])
>> unicode_string = gb2312_bytes.decode('gb2312')
>> utf8_bytes = unicode_string.encode('utf-8') #as you wanted

Simplifying this hack a bit:

gb2312_bytes = u'\xd6\xd0\xce\xc4'.encode('ISO-8859-1')
unicode_string = gb2312_bytes.decode('gb2312')
utf8_bytes = unicode_string.encode('utf-8')

Although I have to wonder why you want a UTF-8 encoded byte string as
output instead of Unicode.


>> If possible, I'd look at the code that's giving you that funky
>> "string" in the first place and see if it can be fixed to give you
>> either a proper bytestring or proper unicode string rather than the
>> bastardized mess you're currently having to deal with.
>
> thanks for the great tips! it works like a charm.

I hope you're aware that it's a big ugly hack, though. You should really
try to fix your input instead.


> i m using the Scrapy project(http://doc.scrapy.org/intro/
> tutorial.html) to write my crawler, when it extract data with xpath,
> it puts the chinese characters directly into the unicode object.

My guess is that the HTML page you are parsing is broken and doesn't
specify its encoding. In that case, all that scrapy can do is guess, and it
seems to have guessed incorrectly.

You should check if there is a way to tell scrapy about the expected page
encoding, so that it can return correctly decoded unicode strings directly,
instead of resorting to dirty hacks that may or may not work depending on
the page you are parsing.

Stefan


==============================================================================
TOPIC: associative array
http://groups.google.com/group/comp.lang.python/t/2cba5368a4df0374?hl=en
==============================================================================

== 1 of 4 ==
Date: Thurs, Apr 1 2010 3:58 am
From: Javier Montoya


On Mar 31, 7:36 pm, Gary Herron <gher...@digipen.edu> wrote:
> JavierMontoyawrote:
> > Dear all,
>
> > I'm a newbie in python and would be acknowledge if somebody could shed
> > some light on associative arrays.
> > More precisely, I would like to create a multi-dimensional associative
> > array. I have for example a list of students which are identified
> > uniquely by their student IDs. Additionally, for each student I have
> > some information: FirstName, LastName, etc.
>
> > The array would have then the following form:
> > [StudentID] => [FirstName][LastName][Telephone]...[ ... ]
>
> > I would like to be able to access a field directly by using a
> > StudentID
> > [StudentID][FirstName]
> > [StudentID][LastName]
>
> > How could I manipulate such an array (create the array, add elements,
> > access data)?
>
> > Best wishes
>
> Create a class for student with attributes for ID, FirstName, LastName, etc.
>
>   class Student:
>       def __init__(self, id, FirstName, ...):
>           self.id = id
>           self.FirstName = FirstName
>           ...
>
> then whenever you create a student object, use a dictionary to associate
> the object with its is
>   AA = {} # An empty dictionary
>   s = Student(...)
>   AA[s.id] = s
>   ... and repeat for many students...
>
> Then to access a student's object given an id:
>   s = AA[id]
>   print s.id, s.FirstName, s.LastName, ...
>
> I'd *not* call this a multi-dimension association, but rather just an
> association between student objects and their ids.
>
> Hope that helps,
>
> Gary Herron
>
> --
> Gary Herron, PhD.
> Department of Computer Science
> DigiPen Institute of Technology
> (425) 895-4418

Dear all,

Thanks for your suggestions, it worked! As Gary suggested, I created a
'student' class and mapped its objects to a dictionary.
Is it possible to sort the dictionary by the student's grades in
descending order?

Best wishes


== 2 of 4 ==
Date: Thurs, Apr 1 2010 4:10 am
From: Chris Rebert


On Thu, Apr 1, 2010 at 3:58 AM, Javier Montoya <jmontoyaz@gmail.com> wrote:
> On Mar 31, 7:36 pm, Gary Herron <gher...@digipen.edu> wrote:
>> JavierMontoyawrote:
>> > Dear all,
>>
>> > I'm a newbie in python and would be acknowledge if somebody could shed
>> > some light on associative arrays.
>> > More precisely, I would like to create a multi-dimensional associative
>> > array. I have for example a list of students which are identified
>> > uniquely by their student IDs. Additionally, for each student I have
>> > some information: FirstName, LastName, etc.
>>
>> > The array would have then the following form:
>> > [StudentID] => [FirstName][LastName][Telephone]...[ ... ]
>>
>> > I would like to be able to access a field directly by using a
>> > StudentID
>> > [StudentID][FirstName]
>> > [StudentID][LastName]
>>
>> > How could I manipulate such an array (create the array, add elements,
>> > access data)?
>>
>> > Best wishes
>>
>> Create a class for student with attributes for ID, FirstName, LastName, etc.
>>
>>   class Student:
>>       def __init__(self, id, FirstName, ...):
>>           self.id = id
>>           self.FirstName = FirstName
>>           ...
>>
>> then whenever you create a student object, use a dictionary to associate
>> the object with its is
>>   AA = {} # An empty dictionary
>>   s = Student(...)
>>   AA[s.id] = s
>>   ... and repeat for many students...
>>
>> Then to access a student's object given an id:
>>   s = AA[id]
>>   print s.id, s.FirstName, s.LastName, ...
>>
>> I'd *not* call this a multi-dimension association, but rather just an
>> association between student objects and their ids.
>>
>> Hope that helps,
>>
>> Gary Herron
>>
>> --
>> Gary Herron, PhD.
>> Department of Computer Science
>> DigiPen Institute of Technology
>> (425) 895-4418
>
> Dear all,
>
> Thanks for your suggestions, it worked! As Gary suggested, I created a
> 'student' class and mapped its objects to a dictionary.
> Is it possible to sort the dictionary by the student's grades in
> descending order?

Dictionaries are not ordered collections, so they themselves cannot be sorted.

However, if you want a list of students sorted in the manner you stated:
class_rank = list(garys_dictionary.values())
class_rank.sort(key=lambda student: student.grade, reverse=True)

Cheers,
Chris
--
http://blog.rebertia.com


== 3 of 4 ==
Date: Thurs, Apr 1 2010 4:20 am
From: Peter Otten <__peter__@web.de>


Javier Montoya wrote:

> Is it possible to sort the dictionary by the student's grades in
> descending order?

You cannot sort dictionaries, but you can put dictionary items into a list
and then sort that.

Assumming that you have a dictionary student_dict that maps student IDs to
Student instances and a function get_grade() to find a student's grade you'd
do

def get_grade(student):
return course[student.student_id].grade # or whatever it takes

students_by_grade = sorted(student_dict.itervalues(), key=get_grade,
reverse=True)

for student in students_by_grade:
print student.first_name, student.last_name

However, problems like the above are normally handled best using a SQL
database, so I recommend that you have a look at

http://docs.python.org/library/sqlite3.html

Peter


== 4 of 4 ==
Date: Thurs, Apr 1 2010 4:57 am
From: Harishankar


On Wed, 31 Mar 2010 09:40:30 -0700, Javier Montoya wrote:

> Dear all,
>
> I'm a newbie in python and would be acknowledge if somebody could shed
> some light on associative arrays.
> More precisely, I would like to create a multi-dimensional associative
> array. I have for example a list of students which are identified
> uniquely by their student IDs. Additionally, for each student I have
> some information: FirstName, LastName, etc.
>
> The array would have then the following form: [StudentID] =>
> [FirstName][LastName][Telephone]...[ ... ]
>
> I would like to be able to access a field directly by using a StudentID
> [StudentID][FirstName]
> [StudentID][LastName]
>
> How could I manipulate such an array (create the array, add elements,
> access data)?
>
> Best wishes

I know this is not a direct answer, but in your case I would probably use
a database, because it is the easiest and most standardized way to access
such types of data. If you don't want something heavyweight, use sqlite
with in-memory databases/persistent file.

Look at sqlite3 module in python.

--
Harishankar (http://harishankar.org http://literaryforums.org)

==============================================================================
TOPIC: decorators only when __debug__ == True
http://groups.google.com/group/comp.lang.python/t/5da23b4a51e9a19e?hl=en
==============================================================================

== 1 of 3 ==
Date: Thurs, Apr 1 2010 5:54 am
From: MRAB


Steven D'Aprano wrote:
> On Thu, 01 Apr 2010 00:27:51 +0100, MRAB wrote:
>
>>>> A decorator shouldn't call the function it's decorating.
>>> *raises eyebrow*
>>>
>>> Surely, in the general case, a decorator SHOULD call the function it is
>>> decorating? I'm sure you know that, but your wording is funny and could
>>> confuse the OP.
>>>
>> What I mean is that the function that's doing the decorating shouldn't
>> call the function; it's the locally-defined wrapper function that calls
>> the decorated function.
>
> Ah, gotcha, that makes sense. Now I understand the distinction you were
> making. Thank you for the clarification.
>
I had the following idea: define the terms 'decorator', 'decoration' and
'decoratee'. The decorator applies the decoration to the decoratee. The
decoratee is the function defined locally in the decorator.


== 2 of 3 ==
Date: Thurs, Apr 1 2010 6:16 am
From: Steve Holden


MRAB wrote:
> Steven D'Aprano wrote:
>> On Thu, 01 Apr 2010 00:27:51 +0100, MRAB wrote:
>>
>>>>> A decorator shouldn't call the function it's decorating.
>>>> *raises eyebrow*
>>>>
>>>> Surely, in the general case, a decorator SHOULD call the function it is
>>>> decorating? I'm sure you know that, but your wording is funny and could
>>>> confuse the OP.
>>>>
>>> What I mean is that the function that's doing the decorating shouldn't
>>> call the function; it's the locally-defined wrapper function that calls
>>> the decorated function.
>>
>> Ah, gotcha, that makes sense. Now I understand the distinction you
>> were making. Thank you for the clarification.
>>
> I had the following idea: define the terms 'decorator', 'decoration' and
> 'decoratee'. The decorator applies the decoration to the decoratee. The
> decoratee is the function defined locally in the decorator.

It would make more sense (to me, at least) if the decoratee were the
function passed as an argument to the decorator.

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
See PyCon Talks from Atlanta 2010 http://pycon.blip.tv/
Holden Web LLC http://www.holdenweb.com/
UPCOMING EVENTS: http://holdenweb.eventbrite.com/

== 3 of 3 ==
Date: Thurs, Apr 1 2010 7:07 am
From: Steve Howell


On Apr 1, 6:16 am, Steve Holden <st...@holdenweb.com> wrote:
> MRAB wrote:
>
> > I had the following idea: define the terms 'decorator', 'decoration' and
> > 'decoratee'. The decorator applies the decoration to the decoratee. The
> > decoratee is the function defined locally in the decorator.
>
> It would make more sense (to me, at least) if the decoratee were the
> function passed as an argument to the decorator.
>

Me too. I do like the idea of coming up with a consistent terminology.

==============================================================================
TOPIC: Python 3.1, object, and setattr()
http://groups.google.com/group/comp.lang.python/t/621c86af4d407a34?hl=en
==============================================================================

== 1 of 1 ==
Date: Thurs, Apr 1 2010 6:46 am
From: Ethan Furman


Greetings!

Perhaps I woke up too early this morning, but this behaviour has me baffled:

Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.

--> test = object()

--> setattr(test, 'example', 123)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'example'

Shouldn't setattr() be creating the 'example' attribute? Any tips
greatly appreciated!

~Ethan~


==============================================================================

You received this message because you are subscribed to the Google Groups "comp.lang.python"
group.

To post to this group, visit http://groups.google.com/group/comp.lang.python?hl=en

To unsubscribe from this group, send email to comp.lang.python+unsubscribe@googlegroups.com

To change the way you get mail from this group, visit:
http://groups.google.com/group/comp.lang.python/subscribe?hl=en

To report abuse, send email explaining the problem to abuse@googlegroups.com

==============================================================================
Google Groups: http://groups.google.com/?hl=en

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate