| | |
Starting Python
![]() |
Python's lambda allows you to declare a one-line nameless minifunction on the fly. The format is:
lambda parameter(s): expression using the parameter(s)
It returns the result of the expression. The expression has to be a one-liner (no newlines)! Here is a little example ...
lambda parameter(s): expression using the parameter(s)
It returns the result of the expression. The expression has to be a one-liner (no newlines)! Here is a little example ...
python Syntax (Toggle Plain Text)
# sort strings in a list, case insensitive import string wordList = ['Python', 'is', 'really', 'great', 'stuff'] print "Original list:" print wordList wordList.sort() print "After standard sort (ASCII upper case is before lower case):" print wordList wordList.sort(lambda x, y: cmp(string.lower(x), string.lower(y))) print "After case insensitve sort with lambda and lower:" print wordList
Last edited by vegaseat; May 15th, 2007 at 6:47 pm. Reason: changed php tags
May 'the Google' be with you!
List comprehension is something Python borrowed from a language called Haskell. It returns a new list and is shorter and simply faster than the traditional loop/append alternative. Look at the two functions and you can get an idea how list comprehension works within the one-line [ ... ].
python Syntax (Toggle Plain Text)
# the module profile is used to compare the two functions import profile def evenList1(): """returns a list of even numbers from 0 to 99998 using append in a loop the 50000 calls to append() consume a lot of CPU time """ L1 = [] for x in range(100000): if x % 2 == 0: L1.append(x) return L1 def evenList2(): """returns a list of even numbers from 0 to 99998 using list comprehension much faster in CPU time than the standard loop with append() """ L2 = [ x for x in range(100000) if x % 2 == 0 ] return L2 # test first 30 elements print evenList1()[0:30] print evenList2()[0:30] print "Profile of evenList1(), check the time consumed by the many append() calls:" print "(ignore time consumed by the profiler itself)\n" profile.run('evenList1()') print "Profile of evenList2():" print "(ignore time consumed by the profiler itself)\n" profile.run('evenList2()')
Last edited by vegaseat; Mar 1st, 2007 at 3:49 pm. Reason: [code=python] tag
May 'the Google' be with you!
Can you figure results?
Python Syntax (Toggle Plain Text)
a, b, c, d, e = range(100, 1000, 200) print a, b, c, d, e
If you have been thinking about some GUI programming using wxPython, one hassle is to properly position and size the widgets (components) on the coordinates of the window. I prefer to use the position (x, y) tuple for the upper left corner of the widget, and the size (width, height) tuple. For example ...
python Syntax (Toggle Plain Text)
# wx.Choice(parent, id, pos, size, choices, style) import wx class MyPanel(wx.Panel): def __init__(self, parent, id): # initial panel fills the frame # pos defaults to (0, 0) and size to (-1, -1) wx.Panel.__init__(self, parent, id) self.SetBackgroundColour("white") # assigning keys-words, style is not used and assumes a default style self.choice1 = wx.Choice(self, -1, pos=wx.Point(10, 10), size=wx.Size(100, 150), choices=tenList) # a little less typing ... #self.choice1 = wx.Choice(self, -1, pos=(10, 10), size=(100, 150), choices=tenList) self.Bind(wx.EVT_CHOICE, self.selChoice1, self.choice1) # simpler, but you have to follow the exact parameter sequence # (parent, id, position_tuple, size_tuple, choices) self.choice2 = wx.Choice(self, -1, (170, 10), (100, 150), oneList) self.Bind(wx.EVT_CHOICE, self.selChoice2, self.choice2) def selChoice1(self, event): item1 = event.GetString() print "choice1 =", item1 # test def selChoice2(self, event): item2 = event.GetString() print "choice2 =", item2 # test oneList = ['one', 'two', 'three', 'four'] tenList = ['ten', 'twenty', 'thirty', 'forty'] app = wx.PySimpleApp() # create a window/frame, no parent, -1 is default ID, title, size # pos is not used and defaults to (0, 0) frame = wx.Frame(None, -1, "wx.Size", size = (400, 310)) MyPanel(frame,-1) frame.Show(True) app.MainLoop()
Last edited by vegaseat; Mar 1st, 2007 at 3:49 pm. Reason: [code=python] tag
May 'the Google' be with you!
If you have a list of tuples, you can sort by the index of the tuple element, as long as the tuples have the same number of elements. In some cases the first element of each tuple can be used as a sorting key. Here is an example showing the different alternatives at your disposal.
python Syntax (Toggle Plain Text)
# sorting a list of tuples by tuple index def sortTupList(myList, n): """sort a list of tuples by tuple index n, returns a new list""" nlist = [(x[n], x) for x in myList] nlist.sort() return [val for (key, val) in nlist] def sortTupList_inplace(myList, n): """sort a list of tuples by tuple index n in-place, myList will change""" myList[:] = [(x[n], x) for x in myList] myList.sort() myList[:] = [val for (key, val) in myList] originalList = [(2, 'ape', 'medium'), (3, 'bull', 'large'), (1, 'cat', 'small')] # make a copy of the original list, beginning to end newList1 = originalList[:] # basic sort in-place, only sorts by first element (index=0) in tuple, list will change # (first element may be used as a sorting key) newList1.sort() print newList1 # [(1, 'cat', 'small'), (2, 'ape', 'medium'), (3, 'bull', 'large')] # make a copy of the original list, beginning to end newList2 = originalList[:] # sort in-place, sorts by specified element (index=2) in tuple, list will change sortTupList_inplace(newList2, 2) print newList2 # [(3, 'bull', 'large'), (2, 'ape', 'medium'), (1, 'cat', 'small')] # sort by specified element (index=1) of the tuple, original list will not change newList3 = sortTupList(originalList, 1) print newList3 # [(2, 'ape', 'medium'), (3, 'bull', 'large'), (1, 'cat', 'small')] # similar to above, but using operator.itemgetter() and sorted() (needs Python24) import operator index1 = operator.itemgetter(1) newList4 = sorted(originalList, key=index1) print newList4 # [(2, 'ape', 'medium'), (3, 'bull', 'large'), (1, 'cat', 'small')]
Last edited by vegaseat; Mar 1st, 2007 at 3:50 pm. Reason: [code=python] tag
May 'the Google' be with you!
I used to program in C/C++ and still scan the forums. It is amazing how many people write functions within a function either by design or mistake caused by poor identation.
In contrast to C/C++ Python does allow you to define functions within a function, but remember that they are local to that function, unless you apply special considerations. Let's take a look ...
In contrast to C/C++ Python does allow you to define functions within a function, but remember that they are local to that function, unless you apply special considerations. Let's take a look ...
python Syntax (Toggle Plain Text)
# define functions within a function def printCircle(radius): """functions defined within this function are strictly local""" def pi(): # pi is built in, but this is for the demonstration return 355/113.0 def circleArea(r): return pi()*r*r def circleCircumference(r): return pi()*2*r # access the local (nested) functions print "A circle with a radius of %f ..." % radius print "... has an area of %f" % circleArea(radius) print "... has a circumference of %f" % circleCircumference(radius) printCircle(1) #print pi() # local, would give NameError: name 'pi' is not defined def func1 () : """a function can return local functions""" def func2 () : print "this is a message from func2" def func3 () : print "this message courtesy of func3" # needed to access the local functions globally return func2, func3 #func2() # would give NameError: name 'func2' is not defined # let Python know that func2 and func3 are in func1 func2, func3 = func1() # now you can call these functions func2() func3()
Last edited by vegaseat; Mar 1st, 2007 at 3:51 pm. Reason: [code=python] tag
May 'the Google' be with you!
This is an example of a word frequency program. It combines a few lines to make it look shorter, but I hope you can still figure it out ...
python Syntax (Toggle Plain Text)
str1 = """Man who run in front of car, get tired. Man who run behind car, get exhausted.""" # create a list of lower case words word_list = str1.lower().split(None) # create a word:frequency dictionary word_freq = {} for word in word_list: # strip any trailing punctuation marks if word[-1:] in ".,!?;:": word = word.rstrip(word[-1:]) word_freq[word] = word_freq.get(word, 0) + 1 # create a sorted list of keys keys = sorted(word_freq.keys()) for word in keys: print "%-10s %d" % (word, word_freq[word])
Last edited by vegaseat; Mar 1st, 2007 at 3:52 pm. Reason: [code=python] tag
May 'the Google' be with you!
This shows you how to start an external file from within Python code. In this case a small Windows media player to play midi or MP3 files. Sorry, the funky graphics display only gets active with .mp3 files. A zip file with the player and a few sample midi files is attached.
python Syntax (Toggle Plain Text)
# play a midi file with an external midiplayer like # the small (32k) BCX created WMPlay5.exe by vegaseat import subprocess import os midi_player = "WMPlay5.exe" # change folder and midi file to your needs midi_folder = "D:/Python24/Atest/Mplay" midi_file = "DGZ1.mid" player = os.path.join(midi_folder, midi_player) midi = os.path.join(midi_folder, midi_file) subprocess.call([player, midi])
Last edited by vegaseat; May 15th, 2007 at 6:48 pm. Reason: replaced php tags
May 'the Google' be with you!
A logic shortcut:
Notice you can even do logic tests like:
Python Syntax (Toggle Plain Text)
x, y, z = 1, 2, 3 # test if y value is between x and z value if x < y < z: print x, y, z # 1 2 3 # same test, longer logic if x < y and y < z: print x, y, z # 1 2 3
Python Syntax (Toggle Plain Text)
if u < w < v < y < x: do some things
![]() |
Similar Threads
- CGPA calculator (Python)
- Beginning: Starting Python (Python)
- Clear the console screen (Python)
- Re: Starting Python (Python)
Other Threads in the Python Forum
- Previous Thread: wxpython GUI issue with database
- Next Thread: error in numpy
| Thread Tools | Search this Thread |
alarm ansi anydbm app assignment backend beginner binary bluetooth character cipher cmd coordinates customdialog cx-freeze data decimals development directory dynamic exe feet file float format function generator getvalue gnu graphics halp handling heads homework http ideas input ip itunes java keycontrol leftmouse line linux list lists loop maintain maze millimeter module mouse number numbers output parsing path pointer prime programming progressbar push py2exe pygame pymailer python queue random recursion recursive schedule screensaverloopinactive script slicenotation sqlite ssh statistics string strings sudokusolver text thread time tlapse tuple ubuntu unicode url urllib urllib2 variable ventrilo vigenere web webservice wikipedia write wxpython xlib xlwt






