Re: [Tutor] Sorting list of tuples in two passes
On 08/29/2011 01:59 AM, Hugo Arts wrote: On Mon, Aug 29, 2011 at 2:19 AM, Dayo Adewunmicontactd...@gmail.com wrote: On 08/28/2011 06:23 PM, Hugo Arts wrote: On Sun, Aug 28, 2011 at 6:43 PM, Dayo Adewunmicontactd...@gmail.com wrote: Hi I have a list of tuples that each have four elements: [(firstName,lastName,userName,gidNumber),(.)] I'm trying to sort this list in two passes. First by gidNumber and then the subgroups by lastName. So far i've only been able to sort by gidNumber. But I can't seem to wrap my mind around lambda, which is what my browsing around seems to indicate is needed to achieve this? Thanks Dayo Python's builtin sort is stable, which means that ordering of items with the same key is preserved. This property means that you can do multiple pass sorting very easily and efficiently just by sorting twice: # we'll simplify the problem a bit and have tuples with just last name and id. l = [('aaa', 1), ('bbb', 1), ('ccc', 1), ('aaa', 2), ('bbb', 2), ('ccc', 2)] l.sort(key=itemgetter(0)) l [('aaa', 1), ('aaa', 2), ('bbb', 1), ('bbb', 2), ('ccc', 1), ('ccc', 2)] l.sort(key=itemgetter(1)) l [('aaa', 1), ('bbb', 1), ('ccc', 1), ('aaa', 2), ('bbb', 2), ('ccc', 2)] We sort by last name first, then sort again by id. As you can see, the sorting of groups with the same id is preserved, and our list is now in the correct order. Hugo It works when I use your example, but I don't understand why it won't work when I use 4-element tuples instead of 2: l = [('wascas','aaa','fdvdfv', 1), ('rtgdsf','bbb','trfg', 1), ('addwe','ccc','esd', 1), ('xasd','aaa','wascaq', 2), ('nhy','bbb','asw', 2), ('','ccc','dgdeg', 2)] l [('wascas', 'aaa', 'fdvdfv', 1), ('rtgdsf', 'bbb', 'trfg', 1), ('addwe', 'ccc', 'esd', 1), ('xasd', 'aaa', 'wascaq', 2), ('nhy', 'bbb', 'asw', 2), ('', 'ccc', 'dgdeg', 2)] l.sort(key=itemgetter(3)) l [('wascas', 'aaa', 'fdvdfv', 1), ('rtgdsf', 'bbb', 'trfg', 1), ('addwe', 'ccc', 'esd', 1), ('xasd', 'aaa', 'wascaq', 2), ('nhy', 'bbb', 'asw', 2), ('', 'ccc', 'dgdeg', 2)] l.sort(key=itemgetter(1)) l [('wascas', 'aaa', 'fdvdfv', 1), ('xasd', 'aaa', 'wascaq', 2), ('rtgdsf', 'bbb', 'trfg', 1), ('nhy', 'bbb', ' asw', 2), ('addwe', 'ccc', 'esd', 1), ('', 'ccc', 'dgdeg', 2)] Also I notice your original list and your end result list are in the same order. Thanks Dayo In my original example, you can shuffle the list before you sort it and it will still work. Try it, with a quick from random import shuffle; shuffle(l). Also, notice that you want to sort by your primary order *last*. I sorted by last name first, then sorted by id second, which means the final list's primary order is by id, and secondary order by last name. So the sorting goes in reverse. In your example, you sort by id first, then last name. So your final list's primary order is by last name. Hugo I tried it this way and it worked nicely: sortedList = sorted(l, key = itemgetter(3,1)) Thank you :-) Dayo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Sorting list of tuples in two passes
Hi I have a list of tuples that each have four elements: [(firstName,lastName,userName,gidNumber),(.)] I'm trying to sort this list in two passes. First by gidNumber and then the subgroups by lastName. So far i've only been able to sort by gidNumber. But I can't seem to wrap my mind around lambda, which is what my browsing around seems to indicate is needed to achieve this? Thanks Dayo import ldap,re from operator import itemgetter,attrgetter l = ldap.initialize(ldap://172.20.0.1;) l.simple_bind_s(,) base_dn = 'ou=People,dc=aust,o=ami-net' filter = '(objectclass=pilotPerson)' attrs = ['uid', 'gidNumber', 'sn', 'cn'] users = l.search_s(base_dn, ldap.SCOPE_ONELEVEL, filter, attrs) def onelist(users): studentspubline = tuple() students2xPubLines = [] for aUser in users: # Get the user details from LDAP userName = aUser[1]['uid'][0] gidNumber = aUser[1]['gidNumber'][0] lastName = aUser[1]['sn'][0] fullName = aUser[1]['cn'][0] # Get first names of users splitFullName = fullName.split() firstName = splitFullName[1] if gidNumber[:1] == '9': studentspubline = userName,lastName,fullName,gidNumber students2xPubLines.append(studentspubline) sortedStudents2x = sorted(students2xPubLines, key=itemgetter(3,2)) for userName,lastName,fullName,gidNumber in sortedStudents2x: print lastName: %s, gidNumber: %s %(lastName, gidNumber) onelist(users) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Sorting list of tuples in two passes
On 08/28/2011 06:23 PM, Hugo Arts wrote: On Sun, Aug 28, 2011 at 6:43 PM, Dayo Adewunmicontactd...@gmail.com wrote: Hi I have a list of tuples that each have four elements: [(firstName,lastName,userName,gidNumber),(.)] I'm trying to sort this list in two passes. First by gidNumber and then the subgroups by lastName. So far i've only been able to sort by gidNumber. But I can't seem to wrap my mind around lambda, which is what my browsing around seems to indicate is needed to achieve this? Thanks Dayo Python's builtin sort is stable, which means that ordering of items with the same key is preserved. This property means that you can do multiple pass sorting very easily and efficiently just by sorting twice: # we'll simplify the problem a bit and have tuples with just last name and id. l = [('aaa', 1), ('bbb', 1), ('ccc', 1), ('aaa', 2), ('bbb', 2), ('ccc', 2)] l.sort(key=itemgetter(0)) l [('aaa', 1), ('aaa', 2), ('bbb', 1), ('bbb', 2), ('ccc', 1), ('ccc', 2)] l.sort(key=itemgetter(1)) l [('aaa', 1), ('bbb', 1), ('ccc', 1), ('aaa', 2), ('bbb', 2), ('ccc', 2)] We sort by last name first, then sort again by id. As you can see, the sorting of groups with the same id is preserved, and our list is now in the correct order. Hugo It works when I use your example, but I don't understand why it won't work when I use 4-element tuples instead of 2: l = [('wascas','aaa','fdvdfv', 1), ('rtgdsf','bbb','trfg', 1), ('addwe','ccc','esd', 1), ('xasd','aaa','wascaq', 2), ('nhy','bbb','asw', 2), ('','ccc','dgdeg', 2)] l [('wascas', 'aaa', 'fdvdfv', 1), ('rtgdsf', 'bbb', 'trfg', 1), ('addwe', 'ccc', 'esd', 1), ('xasd', 'aaa', 'wascaq', 2), ('nhy', 'bbb', 'asw', 2), ('', 'ccc', 'dgdeg', 2)] l.sort(key=itemgetter(3)) l [('wascas', 'aaa', 'fdvdfv', 1), ('rtgdsf', 'bbb', 'trfg', 1), ('addwe', 'ccc', 'esd', 1), ('xasd', 'aaa', 'wascaq', 2), ('nhy', 'bbb', 'asw', 2), ('', 'ccc', 'dgdeg', 2)] l.sort(key=itemgetter(1)) l [('wascas', 'aaa', 'fdvdfv', 1), ('xasd', 'aaa', 'wascaq', 2), ('rtgdsf', 'bbb', 'trfg', 1), ('nhy', 'bbb', ' asw', 2), ('addwe', 'ccc', 'esd', 1), ('', 'ccc', 'dgdeg', 2)] Also I notice your original list and your end result list are in the same order. Thanks Dayo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Running PIL.Image on .svg file
Hi all When i use PIL.Image in this script:http://dpaste.com/163588/ on an .svg file, I get this error:http://dpaste.com/163584/ How do i process .svg files in python? Thanks Dayo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Running PIL.Image on .svg file
Eduardo Vieira wrote: On Tue, Feb 23, 2010 at 7:27 AM, Dayo Adewunmi contactd...@gmail.com wrote: Hi all When i use PIL.Image in this script:http://dpaste.com/163588/ on an .svg file, I get this error:http://dpaste.com/163584/ How do i process .svg files in python? Thanks Dayo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor Hi, svg is not an image (like a bitmap), it's a vector format file, an xml file to be more precise. Ahhh, I see. Ok thanks. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Regex to find files ending with one of a given set of extensions
Steven D'Aprano wrote: On Mon, 22 Feb 2010 04:23:04 am Dayo Adewunmi wrote: Hi all I'm trying use regex to match image formats: Perhaps you should use a simpler way. def isimagefile(filename): ext = os.path.splitext(filename)[1] return (ext.lower() in ('.jpg', '.jpeg', '.gif', '.png', '.tif', '.tiff')) def findImageFiles(): someFiles = [ sdfinsf.png,dsiasd.dgf,wecn.GIF,iewijiefi.jPg,iasjasd.py] return filter(isimagefile, someFiles) $ python test.py Traceback (most recent call last): File test.py, line 25, in module main() File test.py, line 21, in main findImageFiles() File test.py, line 14, in findImageFiles findImages = imageRx(someFiles) TypeError: '_sre.SRE_Pattern' object is not callable The error is the line findImages = imageRx(someFiles) You don't call regexes, you have to use the match or search methods. And you can't call it on a list of file names, you have to call it on each file name separately. # untested for filename in someFiles: mo = imageRx.search(filename) if mo is None: # no match pass else: print filename I incorporated this into my code: def isimagefile(filename): ext = os.path.splitext(filename)[1] return (ext.lower() in ('.jpg', '.jpeg', '.gif', '.png', '.tif', '.tiff')) And it's working fine now. Thanks! :-) Dayo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Regex to find files ending with one of a given set of extensions
Hi all I'm trying use regex to match image formats: import re def findImageFiles(): imageRx = re.compile('\.jpe?g$|\.png$|\.gif$|\.tiff?$', re.I) someFiles = [sdfinsf.png,dsiasd.dgf,wecn.GIF,iewijiefi.jPg,iasjasd.py] findImages = imageRx(someFiles) print START: %s %(findImages.start()) print GROUP: %s %(findImages.group()) def main(): findImageFiles() if __name__ == __main__: main() here's the traceback: $ python test.py Traceback (most recent call last): File test.py, line 25, in module main() File test.py, line 21, in main findImageFiles() File test.py, line 14, in findImageFiles findImages = imageRx(someFiles) TypeError: '_sre.SRE_Pattern' object is not callable i'm new with regexing, please help. Thanks Dayo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] os.path.basename() issue with path slashes
Hi all, This script I'm working on, should take all the image files in the current directory and generate an HTML thumbnails. import os import urllib # Generate thumbnail gallery def genThumbs(): # Get current directory name absolutePath = os.getcwd() urlprefix = http://kili.org/~dayo; currentdir = os.path.basename(absolutePath) for dirname, subdirname, filenames in os.walk(absolutePath): for filename in filenames: print a href=\%s/%s\img src=\%s\%s\ //a %(currentdir,filename,currentdir,filename) # Generate thumbnail gallery genThumbs() However, this is the type of output I get: a href=http://kili.org/~dayo/thumbs/00838_drops_1024x768.jpg;img src=http://kili.org/~dayo\thumbs\00838_drops_1024x768.jpg; //a See how in the url in the src attribute of the img tag the slashes after ~dayo are somehow turned into backslashes, instead of forwardslashes. How come? Best regards Dayo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] os.path.basename() issue with path slashes
Shashwat Anand wrote: snip for dirname, subdirname, filenames in os.walk(absolutePath): for filename in filenames: print a href=\%s/%s\img src=\%s\%s\ //a %(currentdir,filename,currentdir,filename) I see a small typo here. print a href=\%s/%s\img src=\%s\%s\ //a %(currentdir,filename,currentdir,filename) should rather be print a href=\%s/%s\img src=\%s/%s\ //a %(currentdir,filename,currentdir,filename) .. notice the slashes %s/%s in href tag and %s\%s in img tag. filename = '1.jpg' absolutePath = os.getcwd() currentdir = os.path.basename(absolutePath) print a href=\%s/%s\img src=\%s/%s\ //a %(currentdir,filename,currentdir,filename) a href=Desktop/1.jpgimg src=Desktop/1.jpg //a ~l0nwlf Arrrgh. Didn't see that forwardslash I put in there. It's fixed and works now. Thanks! Dayo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] writing HTML code to a variable/file
Hi, I'm extracting data from OpenLDAP, which needs to be formatted into hyperlinks. So far, I can print the generated HTML code: print a href=\http://users.example.com/~; + userName + + lastName + , + firstName + /a However I want to write each line to a file first, so that I can alphabetically sort the links by lastName, before printing them. I've found this snippet: # Let's create a file and write it to disk. filename = test.dat # Let's create some data: done = 0 namelist = [] *while* *not* done: name = raw_input(Enter a name:) *if* type(name) == type(): namelist.append(name) *else*: *break* # Create a file object: # in write mode FILE = open(filename,w) FILE.writelines(namelist) # Alternatively # for name in namelist: # FILE.write(name) FILE.close() # this is icing, you can just exit and this will be # handled automagically. source: http://www.penzilla.net/tutorials/python/fileio/ Going by the above snippet, I will need to write the hyperlink to a variable, e.g. name, which is in turn appended to namelist, and subsequently written to the file. How do I save this a href=\http://users.example.com/~; + userName + + lastName + , + firstName + /a to a variable, then? Thanks Dayo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Triggering code on 1 minute intervale ..
Alex Feddor wrote: .. What will be the best solution to trigger python code every minute as soon as PC in on. Cheers, Alex ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor A cron job? Regards Dayo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to run a .py file or load a module?
David wrote: Norman Khine wrote: On Mon, Apr 27, 2009 at 12:07 AM, Sander Sweers sander.swe...@gmail.com wrote: Here is another one for fun, you run it like python countdown.py 10 #!/usr/bin/env python import sys from time import sleep times = int(sys.argv[1]) # The argument given on the command line def countdown(n): try: while n != 1: n = n-1 print n sleep(1) finally: print 'Blast Off!' countdown(times) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor Thank you all for all your valuable input on this. I have learned so much on this particular subject in such a short time. David, I ran your code, and noticed that given countdown(10) your countdown starts at 9 and Blastoff takes place after 1, not 0. To fix that, I changed while n ! = 1 to while n != 0 and changed n = n - 1 print n to print n n = n -1 Thanks for the time you guys have put into this. It's much appreciated. :-) Dayo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to run a .py file or load a module?
Denis, this mail was very comprehensive, and went a long way of driving it all home for me. There are several different concepts that are involved in this simple problem that I had, and you guys explaining them has really expanded my pythonic horizon, especially the explanations on the argv module, and also the idea of from module import function as saveImportedFuncUnderThisName Thanks a lot, everybody. :-) Dayo -- spir wrote: Le Sun, 26 Apr 2009 22:35:36 +0100, Dayo Adewunmi contactd...@gmail.com s'exprima ainsi: How can I a) Open my shell, and do something like: $ python countdown.py but have it take an argument and pass it to the function, and execute. When your code is (nicely) organised as a set of funcs or class definitions, you also need a laucher usually called main(). Otherwise python only parses and records the definitions into live objects that wait for someone to tell them what they're supposed to do. I'll stick first at processes without any parameter, like if your func would always countdown from 10. There are several use patterns: (1) Program launched from command line. Just add a call to your func: countdown(10) (2) Module imported from other prog Nothing to add to your module. Instead, the importing code needs to hold: import countdown # the module (file) ... countdown.countdown(n) # the func itself or from countdown import countdown # the func, directly ... countdown(n) (3) Both You need to differenciate between launching and importing. Python provides a rather esoteric idiom for that: func def here if __name__ == __main__: countdown(10) The trick is that when a prog is launched directly (as opposed to imported), it silently gets a '__name__' attribute that is automatically set to __main__. So that the one-line block above will only run when the prog is launched, like in case (1). While nothing will happen when the module is imported -- instead the importing code will have the countdown func available under name 'countdown' as expected, like in case (2). Clear? b) Import the function in the interactive interpreter, and call it like so: countdown(10) without getting the abovementioned error. In the case of an import, as your func definition has the proper parameter, you have nothing to change. While for a launch from command-line, you need to get the parameter given by the user. But how? Python provides a way to read the command-line arguments under an attribute called 'argv' of the 'sys' module. argv is a list which zerost item is the name of the file. For instance if called python countdown.py 9 argv holds: ['countdown.py', '9'] Note that both are strings. Then you can catch and use the needed parameter, e.g. from time import sleep as wait from sys import argv as user_args def countdown(n=10): if n = 0: print 'Blastoff!' else: wait(0.333) print n countdown(n-1) def launch(): if len(user_args) == 1: countdown() else: n = int(user_args[1]) countdown(n) if __name__ == __main__: launch() (You can indeed put the content of launch() in the if block. But I find it clearer that way, and it happens to be a common practice.) Denis -- la vita e estrany ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] How to run a .py file or load a module?
I'm looking at recursion in Think Python, and this is the bit of code: #!/usr/bin/env python def countdown(n): if n = 0: print 'Blastoff!' else: print n countdown(n-1) I've typed that in vim and saved as countdown.py, but I'm not sure how to run it. I've had other python files, where the triggering function didn't take any arguments, so I would just put a `foo()` at the end of the .py file. However with this particular function that requires an argument, I'm not sure how to run it. I've had to type it out in the python prompt and then call the function with an argument. That works, naturally. I've also tried this: import countdown countdown(10) but this is the error I get: Traceback (most recent call last): File stdin, line 1, in module NameError: name 'countdown' is not defined How can I a) Open my shell, and do something like: $ python countdown.py but have it take an argument and pass it to the function, and execute. b) Import the function in the interactive interpreter, and call it like so: countdown(10) without getting the abovementioned error. Thanks. Dayo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python books
chinmaya wrote: On Mon, Apr 13, 2009 at 11:07 PM, sudhanshu gautam sudhanshu9...@gmail.com mailto:sudhanshu9...@gmail.com wrote: I am new in python , so need a good books , previously read python Bible and swaroop but not satisfied . so tell me good books in pdf format those contents good problems also ___ Tutor maillist - Tutor@python.org mailto:Tutor@python.org http://mail.python.org/mailman/listinfo/tutor I would say start with python tutorial, its nice decent starting material. There is no better way to learn language than to practice it as you read. Most of the tutorials out there are not written for 3.0, so you may want to install 2.6. I also recommend Dive Into python, its very beginner friendly, but remember it does not cover all (not all major) libraries never-the-less its one of the best beginner tutorial. Also install ipython its very powerful. And once you learn the interface its very easy to find documentation and library references. Also you can look at 100s of python videos in showmedo.com http://showmedo.com -- chinmaya sn ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor I'm currently reading Think Python http://www.greenteapress.com/thinkpython/thinkpython.html Regards Dayo --- ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to compile python3.0
Shaofeng NIu wrote: I tried to compile and install python3.0 from source,but after make,it shows: Python build finished, but the necessary bits to build these modules were not found: _dbm _gdbm _hashlib _sqlite3 _ssl _tkinter bz2readline To find the necessary bits, look in setup.py in detect_modules() for the module's name. Could anybody tell me how to install these modules?Thank you! My OS is Ubuntu 8.10 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor This worked for me on Ubuntu 8.04: $ sudo apt-get install build-essential libncursesw5-dev libreadline5-dev libssl-dev libgdbm-dev libbz2-dev libc6-dev libsqlite3-dev tk-dev g++ gcc Solution for _dbm $ wget -c http://bugs.python.org/file12234/dbm.diff $ patch -p0 dbm.diff $ sudo apt-get build-dep python2.5 $ make $ sudo make install Regards Dayo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] PDF to text conversion
Emile van Sebille wrote: Robert Berman wrote: snip Have any of you worked with such a library, or do you know of one or two I can download and work with? Hopefully, they have reasonable documentation. My development environment is: Python Linux Ubuntu version 8.10 I've used [r...@fcfw2 /]# /usr/bin/pdftotext -v pdftotext version 2.01 Copyright 1996-2002 Glyph Cog, LLC [r...@fcfw2 /]# cat /etc/issue Red Hat Linux release 9 (Shrike) HTH, Emile ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor Hi Robert, pdftotext is part of poppler-utils, an Ubuntu package which can be installed like so: sudo aptitude install poppler-utils But I to would be interested in finding a python library/module for this. Regards, Dayo ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor