[Tutor] Tutor Digest, Vol 109, Issue 71
Matthew Johnson
mcooganj at gmail.com
Thu Mar 21 02:14:28 CET 2013
I recently asked a question on SO:
http://stackoverflow.com/questions/15180767/subset-list-based-on-value-of-dictionary-element
and got very confused when trying to generalise the answer.
The problem is as follows:
say i have this list, and would like to get the value at each date that has
the largest value for realtime_start (date) value.
obs = [{'date': '2012-10-01',
'realtime_end': '2013-02-18',
'realtime_start': '2012-11-15',
'value': '231.751'},
{'date': '2012-10-01',
'realtime_end': '9999-12-31',
'realtime_start': '2012-12-19',
'value': '231.623'},
{'date': '2012-11-01',
'realtime_end': '2013-02-18',
'realtime_start': '2012-12-14',
'value': '231.025'},
{'date': '2012-11-01',
'realtime_end': '9999-12-31',
'realtime_start': '2013-01-19',
'value': '231.071'},
{'date': '2012-12-01',
'realtime_end': '2013-02-18',
'realtime_start': '2013-01-16',
'value': '230.979'},
{'date': '2012-12-01',
'realtime_end': '9999-12-31',
'realtime_start': '2013-02-19',
'value': '231.137'},
{'date': '2012-12-01',
'realtime_end': '9999-12-31',
'realtime_start': '2013-03-19',
'value': '231.197'},
{'date': '2013-01-01',
'realtime_end': '9999-12-31',
'realtime_start': '2013-02-21',
'value': '231.198'},
{'date': '2013-01-01',
'realtime_end': '9999-12-31',
'realtime_start': '2013-03-21',
'value': '231.222'}]
maxDate = "2013-02-21"
The answer suggested itertools, and it worked for the exact maxDate that's
above.
However, when i move the date (say to "2013-01-21") it throws the error:
ValueError: max() arg is an empty sequence.
I can see from the list that there are elements
that have realtime_start values that are lower than 2013-01-21 so this is a
bug.
I have read the documents for itertools, but cannot quite work out this
groupby stuff.
there's a snip of the SO solution below -- help understanding as well as
the bug fix would be much appreciated.
thanks in advance,
Matt Johnson
______
## subset on maxDate
grouped2 = itertools.groupby(obs, lambda x: x['date'])
m2 = [max((w for w in g if w['realtime_start'] <= maxDate),
key=lambda x: x['realtime_start']) for k, g in grouped2]
pprint.pprint(m2)
On 21/03/2013, at 8:30 AM, "tutor-request at python.org" <
tutor-request at python.org> wrote:
Send Tutor mailing list submissions to
tutor at python.org
To subscribe or unsubscribe via the World Wide Web, visit
http://mail.python.org/mailman/listinfo/tutor
or, via email, send a message with subject or body 'help' to
tutor-request at python.org
You can reach the person managing the list at
tutor-owner at python.org
When replying, please edit your Subject line so it is more specific
than "Re: Contents of Tutor digest..."
Today's Topics:
1. Re: Help (Dave Angel)
2. Re: Help (xDog Walker)
3. Re: Help (Robert Sjoblom)
4. Re: Scripting Calligra sheets with Python (Jim Byrnes)
5. Re: Help (Alan Gauld)
----------------------------------------------------------------------
Message: 1
Date: Wed, 20 Mar 2013 16:53:19 -0400
From: Dave Angel <davea at davea.name>
To: tutor at python.org
Subject: Re: [Tutor] Help
Message-ID: <514A21BF.9030303 at davea.name>
Content-Type: text/plain; charset=ISO-8859-1; format=flowed
On 03/20/2013 03:57 PM, travis jeanfrancois wrote:
Hello, I am a beginning python student and I am having trouble with a
program I am writing . The problem requires me to use "while" and that I
create a function that allows the user to a create sentence by inputing a
string and to end the sentence with a period meaning inputing "." .The
problem is while keeps overwriting the previuos input and it still asks for
a string even after it prints out .
Here is the output I am getting
Enter the first word in your sentence: I
Enter the next word in your sentence: am
Enter the next word in your sentence: a
Enter the next word in your sentence: novice
Enter the next word in your sentence: .
I . .
Enter the next word in your sentence:
Here is the desired output:
:
Enter the first word in your sentence: I
Enter the next word in your sentence: am
Enter the next word in your sentence: a
Enter the next word in your sentence: novice
Enter the next word in your sentence: .
I am a novice.
Here is my code:
def B1():
#Creates a function called B1
period = "."
# The variable period is assigned
first = input("Enter the first word in your sentence ")
#The variable first is assigned
next1 = input("Enter the next word in you sentence or enter period:")
#The variable next 1 is assigned
# I need store the value so when while overwrites next1 with the next
input the previous input is stored and will print output when I call it
later along with last one
# I believe the solution is some how implenting this expression x = x+
variable
You need a new variable that accumulates the whole sentence. I'd use a
list, but many people would use a string. Since I don't know what
concepts you know yet, I'll stick to string here. Anyway, you have to
initialize it before the loop, and then you can print it after the loop.
sentence = ""
while next1 != (period) :
next1 = input("Enter the next word in you sentence or enter period:")
At this point, add the word to the sentence.
if next1 == (period):
next1 = next1 + period
print ("Your sentence is:",first,next1,period)
No need for these three lines inside the loop, since the loop will end
when next1 is equal to the period. So put the print after the end of
the loop, and I'll let you figure out what it should print.
PS : The" #" is I just type so I can understand what each line does
--
DaveA
------------------------------
Message: 2
Date: Wed, 20 Mar 2013 14:47:39 -0700
From: xDog Walker <thudfoo at gmail.com>
To: tutor at python.org
Subject: Re: [Tutor] Help
Message-ID: <201303201447.39643.thudfoo at gmail.com>
Content-Type: text/plain; charset="iso-8859-1"
On Wednesday 2013 March 20 13:39, Robert Sjoblom wrote:
A word of advice: next is a keyword in python
~/Packages/Python/Notable-0.1.5b> python
Python 2.5 (r25:51908, May 25 2007, 16:14:04)
[GCC 4.1.2 20061115 (prerelease) (SUSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
import keyword
keyword.iskeyword('next')
False
14:44 Wed 2013 Mar 20
~/Packages/Python/Notable-0.1.5b> python2.7
Python 2.7.2 (default, Oct 10 2011, 10:47:36)
[GCC 4.1.2 20061115 (prerelease) (SUSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
import keyword
keyword.iskeyword('next')
False
14:44 Wed 2013 Mar 20
~/Packages/Python/Notable-0.1.5b> python3.3
Python 3.3.0 (default, Sep 30 2012, 09:02:56)
[GCC 4.1.2 20061115 (prerelease) (SUSE Linux)] on linux
Type "help", "copyright", "credits" or "license" for more information.
import keyword
keyword.iskeyword('next')
False
--
Yonder nor sorghum stenches shut ladle gulls stopper torque wet
strainers.
------------------------------
Message: 3
Date: Wed, 20 Mar 2013 22:59:04 +0100
From: Robert Sjoblom <robert.sjoblom at gmail.com>
To: xDog Walker <thudfoo at gmail.com>
Cc: Tutor - python List <tutor at python.org>
Subject: Re: [Tutor] Help
Message-ID:
<CAJKU7g2bdCHgza-48xw+5C_7kq592G=p3qxHbE61dUqZQcoTuA at mail.gmail.com>
Content-Type: text/plain; charset="iso-8859-1"
On Mar 20, 2013 10:49 p.m., "xDog Walker" <thudfoo at gmail.com> wrote:
On Wednesday 2013 March 20 13:39, Robert Sjoblom wrote:
A word of advice: next is a keyword in python
~/Packages/Python/Notable-0.1.5b> python
Python 2.5 (r25:51908, May 25 2007, 16:14:04)
[GCC 4.1.2 20061115 (prerelease) (SUSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
import keyword
keyword.iskeyword('next')
False
14:44 Wed 2013 Mar 20
~/Packages/Python/Notable-0.1.5b> python2.7
Python 2.7.2 (default, Oct 10 2011, 10:47:36)
[GCC 4.1.2 20061115 (prerelease) (SUSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
import keyword
keyword.iskeyword('next')
False
14:44 Wed 2013 Mar 20
~/Packages/Python/Notable-0.1.5b> python3.3
Python 3.3.0 (default, Sep 30 2012, 09:02:56)
[GCC 4.1.2 20061115 (prerelease) (SUSE Linux)] on linux
Type "help", "copyright", "credits" or "license" for more information.
import keyword
keyword.iskeyword('next')
False
--
Yonder nor sorghum stenches shut ladle gulls stopper torque wet
strainers.
Fine, it's a method, my bad.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <
http://mail.python.org/pipermail/tutor/attachments/20130320/b646443c/attachment-0001.html
>
------------------------------
Message: 4
Date: Wed, 20 Mar 2013 19:26:54 -0500
From: Jim Byrnes <jf_byrnes at comcast.net>
To: tutor at python.org
Subject: Re: [Tutor] Scripting Calligra sheets with Python
Message-ID: <kidk4b$3po$1 at ger.gmane.org>
Content-Type: text/plain; charset=ISO-8859-1; format=flowed
On 03/19/2013 09:16 PM, Jim Byrnes wrote:
On 03/18/2013 11:25 PM, Dave Angel wrote:
On 03/18/2013 09:56 PM, Jim Byrnes wrote:
On 03/18/2013 07:54 PM, Dave Angel wrote:
On 03/18/2013 12:18 PM, Jim Byrnes wrote:
I am trying to script Calligra Sheets (formerly KSpread) with
python. I
have gotten some of the included example scripts to run so I know
python
scripting is running.
I found the following snippet on their website:
import KSpread
sheet = KSpread.view().sheet()
# swap text of B5 and C6
t1 = sheet.text("B5")
t2 = sheet.text(6,3)
sheet.setText("B5", t2)
sheet.setText(6, 3, t1)
# swap value of D7 and E8
v1 = sheet.value("D7")
v2 = sheet.value(8,5)
sheet.setValue("D7", v2)
sheet.setValue(8, 5, v1)
Error: 'str' object has no attribute 'text'
File
"file:///usr/share/kde4/apps/sheets/scripts/extensions/myswap.py",
line
4, in <module>
This error message appeared in a dialog box.
I've taught myself some Python but I don't understand what is
happening
here. Shouldn't t1 be a sheet object? What would cause it to be a
str
instead?
Since somebody has censored the rest of the error traceback, we can't
even tell what line is giving the error. Assuming you know it's
t1 = sheet.text("85")
I think line wrapping obscured that it is line 4 t1 = sheet.text("B5").
I saw the line 4, but didn't see anyplace where it showed me line 4. So
i had to guess. And for all I knew, the error isn't happening on that
line, but on some line called indirectly by that one. The full stack
trace would be reassuring. But apparently your Calligra environment is
censoring it.
then it has nothing to do with the type of t1, but with the type of
sheet. If that's the case, then print out type(sheet) and see what it
actually is. Then consult the documentation for the
KSpread.view().sheet() function and see what it's documented to return.
The docs say: Returns the KSpread::ViewAdaptor object in which the
document is displayed.
I would like to follow your advice and print out type(sheet) but right
now I don't know how. This is all running inside Calligra sheets and so
far the only thing I have gotten out if it is the error message.
Are you permitted to edit this myswap.py file? If so, add a line that
prints the useful information immediately before the line which causes
the exception. And if print is also swallowed by your helpful
environment, then write to a file.
Yes I can and it does swallow it, so I redirected to a file and it says
<type 'str'>. Same as the error message. So now I need to figure out
why it's not returning the object expected.
I can run the sample scripts that were installed but not something I
originate. I guess I must be missing something procedural that is
keeping them from running properly.
Thanks for you help.
Regards, Jim
Just a follow up for completeness in case some else finds this and has
the same problem.
Replace line 2 sheet = KSpread.view().sheet()
with
sheetname = KSpread.currentSheet().sheetName()
sheet = KSpread.sheetByName(sheetname)
Then it will run with no errors.
Regards, Jim
------------------------------
Message: 5
Date: Thu, 21 Mar 2013 00:26:56 +0000
From: Alan Gauld <alan.gauld at btinternet.com>
To: tutor at python.org
Subject: Re: [Tutor] Help
Message-ID: <kidk4d$3qc$1 at ger.gmane.org>
Content-Type: text/plain; charset=ISO-8859-1; format=flowed
On 20/03/13 19:57, travis jeanfrancois wrote:
I create a function that allows the user to a create sentence by
inputing a string and to end the sentence with a period meaning
inputing "." .The problem is while keeps overwriting the previuos input
'While' does not do any such thing. Your code is doing that all by
itself. What while does is repeat your code until a condition
becomes false or you explicitly break out of the loop.
Here is my code:
def B1():
Try to give your functions names that describe what they do.
B1() is meaningless, readSentence() would be better.
period = "."
# The variable period is assigned
Its normal programming practice to put the comment above
the code not after it. Also comments should indicate why you
are doing something not what you are doing - we can see that
from the code.
first = input("Enter the first word in your sentence ")
next1 = input("Enter the next word in you sentence or enter period:")
# I need store the value so when while overwrites next1 with the next
input the previous input is stored and will print output when I call it
later along with last one
# I believe the solution is some how implenting this expression x = x+
variable
You could be right. Addition works for strings as well as numbers.
Although there are other (better) options but you may not have covered
them in your class yet.
while next1 != (period) :
You don;t need the parentheses around period.
Also nextWord might be a better name than next1.
Saving 3 characters of typing is not usually worthwhile.
next1 = input("Enter the next word in you sentence or enter period:")
Right, here you are overwriting next1. It's not the while's
fault - it is just repeating your code. It is you who are
overwriting the variable.
Notice that you are not using the first that you captured?
Maybe you should add next1 to first at some point? Then you
can safely overwrite next1 as much as you like?
if next1 == (period):
Again you don;t need the parentheses around period
next1 = next1 + period
Here, you add the period to next1 which the 'if' has
already established is now a period.
print ("Your sentence is:",first,next1,period)
And now you print out the first word plus next1 (= 2 periods) plus a
period = 3 periods in total... preceded by the phrase "Your sentence
is:" This tells us that the sample output you posted is not from this
program... Always match the program and the output when debugging or you
will be led seriously astray!
PS : The" #" is I just type so I can understand what each line does
The # is a comment marker. Comments are a very powerful tool that
programmers use to explain to themselves and other programmers
why they have done what they have.
When trying to debug faults like this it is often worthwhile
grabbing a pen and drawing a chart of your variables and
their values after each time round the loop.
In this case it would have looked like
iteration period first next1
0 . I am
1 . I a
2 . I novice
3 . I ..
If you aren't sure of the values insert a print statement
and get the program to tell you, but working it out in
your head is more likely to show you the error.
HTH,
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
------------------------------
Subject: Digest Footer
_______________________________________________
Tutor maillist - Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor
------------------------------
End of Tutor Digest, Vol 109, Issue 71
**************************************
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130321/cee97e15/attachment-0001.html>
More information about the Tutor
mailing list