| | |
Starting Python
![]() |
For Python 2.x:
People seem to overlook the usefulness of built-in functions for handling common issues with lists. A lot of times,
With reduce, note that it is redundant to use this to sum all the indices in a list, as there is a built-in function for that,
Python docs' examples of these three functions.
People seem to overlook the usefulness of built-in functions for handling common issues with lists. A lot of times,
filter , map , and reduce can easily and efficiently serve typical purposes that most people attempt without these. Here's an example of their usage (I use lambda expressions in them - you can read up on lambda expressions here): python Syntax (Toggle Plain Text)
# filter # in the interactive shell, use help(filter) for more info. # filter takes a function and a list, and returns a list of # the items that returned True for the given function. # This example takes a list and returns one with the # unallowed words removed. words = ['This', 'sentence', 'has', 'unallowed', 'words'] unallowed = ['has', 'words'] remainder = filter(lambda x: x not in unallowed, words) """result -> ['This', 'sentence', 'unallowed'] """
python Syntax (Toggle Plain Text)
# map # in the interactive shell, use help(map) for more info. # map takes a function and a list, and returns a list of # the items after applying the specified function to them. # This example takes a list and returns one in which # every index was squared. data = [2, 5, 9, 16, 31, 35] squared = map(lambda x: x*x, data) """result -> [4, 25, 81, 256, 961, 1225] """
python Syntax (Toggle Plain Text)
# reduce # in the interactive shell, use help(reduce) for more info. # reduce takes a function and a list, and returns a single # value formed by taking the result of the function on the # first two indices, then applying the function on that result # and the third index, and so forth. # This example takes a list and returns an integer calculated # by multiplying all the indices together. data = [1, 3, 4, 7, 8, 9] reduce(lambda x, y: x * y, data) """result -> 6048 """
sum . (This is because getting the sum of a list is such a common need.)Python docs' examples of these three functions.
Last edited by shadwickman; Jul 2nd, 2009 at 12:58 am.
"Two good old boys in a fire-apple red convertible. Stoned. Ripped. Twisted. Good people."
- Hunter S. Thompson
my photography
- Hunter S. Thompson
my photography
This code shows you how to get file information of a given folder into a table. It also is modified to work with Linux or Windows, as these Operating Systems have differences in some of the file functions and folder syntax:
python Syntax (Toggle Plain Text)
# File_Info2.py # show some file details in a table # note that Linux file names are case sensitive # Linux uses different folder syntax and getctime() for last changes # Windows uses getmtime() for last changes/modifications # this program has been written to accept Windows or Linux # tested with Python 2.5.4 import os import time import sys # check if your OS is linux or windows # pick an appropriate folder/directory you have if sys.platform[:5] == "linux": folder = "/home/dell/Atest25/Chemistry" win_flag = False else: folder = 'C:/Python25/Atest25/Chemistry' win_flag = True #print(win_flag) # test # create list of (fname, size, date_time) tuples file_info = [] for item in os.listdir(folder): # get full path for isdir() to work path = os.path.join(folder, item) # make sure item is a filename if os.path.isdir(path): continue # skip any folder names if win_flag: change = os.path.getmtime(path) # Windows else: change = os.path.getctime(path) # Linux # (year,month,day,hour,min,sec,weekday(Monday=0),yearday,dlsflag) # eg. (2009, 7, 31, 21, 37, 6, 4, 212, 1) change_tuple = time.localtime(change) date_time24 = time.strftime("%m/%d/%Y %H:%M:%S", change_tuple) size = os.path.getsize(path) # convert to kb if size > 999: size = round(size/1024.0, 1) else: size = round(size/1024.0, 3) file_info.append((os.path.basename(path), size, date_time24)) # show result as formatted table ... # for longer file names use eg. "%-36s %8s %s" fs = "%-25s %8s %s" print(fs % (' Name', 'Size (kb)', ' Date&Time (24hr)')) for line in file_info: print(fs % line) """my output example --> Name Size (kb) Date&Time (24hr) MWcalc2a.py 3.2 05/10/2009 10:21:51 PeriodicTable1.py 5.6 06/04/2009 17:12:15 CONST.TXT 1.0 05/10/2009 10:21:51 ELEMORDR.TXT 0.417 05/10/2009 10:21:51 AirEarth.txt 1.5 05/10/2009 10:21:51 ELEMENT9.TXT 11.2 05/10/2009 10:21:51 ChemHelp.exe 237.0 05/10/2009 10:21:51 wxgridGrid3_solvents.pyw 4.7 06/04/2009 17:12:15 MWcalc1.py 3.2 05/10/2009 10:21:51 CHEMICAL.BMP 43.2 05/10/2009 10:21:51 MWtable1.py 2.4 05/10/2009 10:21:51 """
No one died when Clinton lied.
Python31 is joy, here I am exploring named tuples and ordered dictionaries and their interconnection:
python Syntax (Toggle Plain Text)
# some play with named tuples and ordered dictionaries # needs Python3 import collections as co # set up named tuple where staff is the identifier # and the field names are fname, sname, age ntup = co.namedtuple('staff', 'fname, sname, age') # load the tuple nt1 = ntup('Hank', 'Zoller', 27) nt2 = ntup('Bjorn', 'Bartok', 34) # this would give an error, not enough args #nt3 = ntup('Jack', 'Schiett') # show the named tuple print(nt1) # staff(fname='Hank', sname='Zoller', age=27) print(nt2) # staff(fname='Bjorn', sname='Bartok', age=34) print(nt2.fname) # Bjorn print(nt2.age) # 34 # show the field names print(nt1._fields) # ('fname', 'sname', 'age') # replace/update items by field name nt4 = nt1._replace(sname='Zeller', age=28) print(nt1) # staff(fname='Hank', sname='Zoller', age=27) print(nt4) # staff(fname='Hank', sname='Zeller', age=28) # convert to ordered dictionary odict = nt2._asdict() print(odict) # convert ordered dictionary to regular dictionary print(dict(odict)) # pop the last item odict.popitem() print(odict) print(odict['sname']) """my output --> OrderedDict([('fname', 'Bjorn'), ('sname', 'Bartok'), ('age', 34)]) {'age': 34, 'sname': 'Bartok', 'fname': 'Bjorn'} OrderedDict([('fname', 'Bjorn'), ('sname', 'Bartok')]) Bartok """ # convert dictionary to named tuple d = {'age': 34, 'sname': 'Bartok', 'fname': 'Bjorn'} nt5 = ntup(**d) print(nt5) # staff(fname='Bjorn', sname='Bartok', age=34)
Last edited by bumsfeld; Aug 2nd, 2009 at 5:49 pm.
Should you find Irony, you can keep her!
•
•
Join Date: Jun 2007
Posts: 3
Reputation:
Solved Threads: 0
My favorite part of python is regular expressios: Here is a nice example you could use:
Like creating a program that searches a database:
import re
a = re.compile("(^(?:0?[1-9]:[0-5]|1"
r"(?=[012])\d:[0-5])\d"
r"(\s)(AM|PM))$")
b = re.compile(r"(-?[1-9]\d?[\w])$|^\d$")
c = re.compile(r"^(\[('([A-Z]|[a-z])'"
r"(,\s'([A-Z]|[a-z])')*"
r")*\])$")
print "----Part a tests that match:"
print a.search("1:45 PM")
print a.search("10:36 AM")
print a.search("12:00 PM")
print a.search("11:59 AM")
print a.search("8:27 AM")
print "----Part a tests that do not match:"
print a.search("21:45 PM")
print a.search("13:36 AM")
print a.search("12:00 XM")
print a.search("11:59 AP")
print a.search("8:3 AM")
print a.search("1:23PM")
print a.search("3:62 PM")
print "----Part b tests that match:"
print b.search("0")
print b.search("5")
print b.search("-16")
print b.search("1873")
print b.search("-89345")
print "----Part b tests that do not match:"
print b.search("X")
print b.search("-0")
print b.search("00")
print b.search("007")
print b.search("-000")
print b.search("-3453!")
print "----Part c tests that match:"
print c.search("['H', 'e', 'l', 'l', 'o']")
print c.search("['H']")
print c.search("['H', 'e']")
print c.search("[]")
print c.search("['C', 'S', 'S', 'E']")
print "----Part c tests that do not match:"
print c.search("['H', 'e', 'l', '7', 'o']")
print c.search("['H', 'e', 'l', 'l', 'o'")
print c.search("['H', 'e', 'l', 'l', 'o',]")
print c.search("['H', 'e', 'l', 'l', 'o' ]")
print c.search("[ 'H', 'e', 'l', 'l', 'o']")
print c.search("['H', 'e', 'lf', 'l', 'o']")
print c.search("[ ]")
print c.search("['H', ]")
print c.search("['5']")
print "----Part d tests that do not match:"
print d.search("901 12th Ave.\nSeattle, WA 98122")
print d.search("901 12th Ave.\nSeattle, WA 98122-1090")
print d.search("1 12th Ave.\nMy City, WA 98122")
print d.search("12 12th Ave.\nSeattle, WA 98122")
print d.search("9 E B&O St.\nB R F, CO 12345")
print d.search("123345 12th Ave.\nSeattle, WA 98122")
print "----Part d tests that do not match:"
print d.search("901 12th Ave.\nSeattle, WA 9812")
print d.search("901 12th Ave.\nSeattle, WA 98122-100")
print d.search("901A 12th Ave.\nSeattle, WA 98122-1090")
print d.search("901 12th Ave.\nSeattle, WAX 98122")
print d.search("901 12th Ave.\nSeattle WA 98122")
print d.search("901 12th Ave.\nSeattle,WA 98122")
print d.search("901 12th Ave.\n\nSeattle, WA 98122")
print d.search("901 12th Ave.\nSeattle, WA 981221090")
print d.search("0 12th Ave.\nSeattle, WA 98122")
Like creating a program that searches a database:
import re
a = re.compile("(^(?:0?[1-9]:[0-5]|1"
r"(?=[012])\d:[0-5])\d"
r"(\s)(AM|PM))$")
b = re.compile(r"(-?[1-9]\d?[\w])$|^\d$")
c = re.compile(r"^(\[('([A-Z]|[a-z])'"
r"(,\s'([A-Z]|[a-z])')*"
r")*\])$")
print "----Part a tests that match:"
print a.search("1:45 PM")
print a.search("10:36 AM")
print a.search("12:00 PM")
print a.search("11:59 AM")
print a.search("8:27 AM")
print "----Part a tests that do not match:"
print a.search("21:45 PM")
print a.search("13:36 AM")
print a.search("12:00 XM")
print a.search("11:59 AP")
print a.search("8:3 AM")
print a.search("1:23PM")
print a.search("3:62 PM")
print "----Part b tests that match:"
print b.search("0")
print b.search("5")
print b.search("-16")
print b.search("1873")
print b.search("-89345")
print "----Part b tests that do not match:"
print b.search("X")
print b.search("-0")
print b.search("00")
print b.search("007")
print b.search("-000")
print b.search("-3453!")
print "----Part c tests that match:"
print c.search("['H', 'e', 'l', 'l', 'o']")
print c.search("['H']")
print c.search("['H', 'e']")
print c.search("[]")
print c.search("['C', 'S', 'S', 'E']")
print "----Part c tests that do not match:"
print c.search("['H', 'e', 'l', '7', 'o']")
print c.search("['H', 'e', 'l', 'l', 'o'")
print c.search("['H', 'e', 'l', 'l', 'o',]")
print c.search("['H', 'e', 'l', 'l', 'o' ]")
print c.search("[ 'H', 'e', 'l', 'l', 'o']")
print c.search("['H', 'e', 'lf', 'l', 'o']")
print c.search("[ ]")
print c.search("['H', ]")
print c.search("['5']")
print "----Part d tests that do not match:"
print d.search("901 12th Ave.\nSeattle, WA 98122")
print d.search("901 12th Ave.\nSeattle, WA 98122-1090")
print d.search("1 12th Ave.\nMy City, WA 98122")
print d.search("12 12th Ave.\nSeattle, WA 98122")
print d.search("9 E B&O St.\nB R F, CO 12345")
print d.search("123345 12th Ave.\nSeattle, WA 98122")
print "----Part d tests that do not match:"
print d.search("901 12th Ave.\nSeattle, WA 9812")
print d.search("901 12th Ave.\nSeattle, WA 98122-100")
print d.search("901A 12th Ave.\nSeattle, WA 98122-1090")
print d.search("901 12th Ave.\nSeattle, WAX 98122")
print d.search("901 12th Ave.\nSeattle WA 98122")
print d.search("901 12th Ave.\nSeattle,WA 98122")
print d.search("901 12th Ave.\n\nSeattle, WA 98122")
print d.search("901 12th Ave.\nSeattle, WA 981221090")
print d.search("0 12th Ave.\nSeattle, WA 98122")
Let's assume you want to sort a list of dictionaries by the value of a given key. The module operator will be of great help ...
python Syntax (Toggle Plain Text)
# sorting a list of dictionaries by the value of a specific key import operator as op # list of {function, priority} dictionaries staff = [ {'function' : 'waiter', 'priority' : 3}, {'function' : 'cook', 'priority' : 1}, {'function' : 'janitor', 'priority' : 4}, {'function' : 'cashier', 'priority' : 2} ] # sort list by the values of key 'priority' staff2 = [] for dic in sorted(staff, key=op.itemgetter('priority')): staff2.append(dic) print(staff2) """my prettied result --> [ {'function': 'cook', 'priority': 1}, {'function': 'cashier', 'priority': 2}, {'function': 'waiter', 'priority': 3}, {'function': 'janitor', 'priority': 4} ] """
Last edited by vegaseat; Aug 9th, 2009 at 2:56 pm.
May 'the Google' be with you!
Or, sort a list of class objects by an attribute (similar idea as above):
python Syntax (Toggle Plain Text)
import operator import string def normcaps(strg): s = string.upper(strg[0]) + strg[1:] return s class Man: def __init__(self,name,pos,age): self.name = name.lower() self.pos = pos.lower() self.age = age def __getitem__(self,key): return self.__dict__[key] def __repr__(self): return self.__str__() def __str__(self): print_name = normcaps(self.name) print_pos = normcaps(self.pos) s = "%s - %s - %s" %(print_name,print_pos,self.age) return s bill = Man('bill','CEO',65) zach = Man('zach','intern',19) jerry = Man('jerry','alpha',52) man_list = [jerry,bill,zach] get_age = operator.itemgetter('age') get_pos = operator.itemgetter('pos') get_name = operator.itemgetter('name') by_age = sorted(man_list,key = get_age) by_name = sorted(man_list,key = get_name) by_pos = sorted(man_list,key = get_pos) print man_list print by_age print by_name print by_pos
Last edited by zachabesh; Aug 14th, 2009 at 8:36 pm.
-Zac
With the introduction of Python version 3 a number of builtins (functions, methods, classes, ...) have been removed and others added. Here is a way to look at the differences.
First create a file of 'builtins' in Python25 ...
... now the 'builtins' in Python31 ...
After we have written the two files we want Python to look at them and show us which 'builtins' are unique for each version ...
First create a file of 'builtins' in Python25 ...
python Syntax (Toggle Plain Text)
# write a sorted 'list' of all Python builtins # (does not include statements) to a file (run with Python 2.5.4) fout = open("Builtins25.txt", "w") print >> fout, '\n'.join(sorted(dir(__builtins__), key=str.lower))
python Syntax (Toggle Plain Text)
# write a sorted 'list' of all Python builtins # (does not include statements) to a file (run with Python 3.1) fout = open('Builtins31.txt', 'w') print('\n'.join(sorted(dir(__builtins__), key=str.lower)), file=fout)
python Syntax (Toggle Plain Text)
# use Python module difflib to find the line by # line differences between two text files # modified to work with Python25 and Python31 """ technical details ... the difflib result will be a list of all lines with a marker prefix followed by a space for each original line - line unique to text list 1 + line unique to text list 2 space marks a line common to both text lists ? extra line used to point out character differences in lines + pointer --> word has extra char, ^ pointer --> spelling, - pointer --> word has missing char """ import difflib lines25 = open("Builtins25.txt").readlines() lines31 = open("Builtins31.txt").readlines() # set up module difflib diff_instance = difflib.Differ() diff_list = list(diff_instance.compare(lines25, lines31)) # testing ... #for line in diff_list: print(line.rstrip()) # lines unique to lines25 unique25 = "" for line in diff_list: if line[0] == '-': unique25 += line[2:] # lines unique to lines31 unique31 = "" for line in diff_list: if line[0] == '+': unique31 += line[2:] print('-'*48) print("Builtins unique to Python25 and not in Python31:") print(unique25) print('-'*48) print("Builtins unique to Python31 and not in Python25:") print(unique31) """my result --> ------------------------------------------------ Builtins unique to Python25 and not in Python31: apply basestring buffer callable cmp coerce execfile file intern long raw_input reduce reload StandardError unichr unicode xrange ------------------------------------------------ Builtins unique to Python31 and not in Python25: __build_class__ __package__ ascii bin BufferError bytearray bytes BytesWarning exec format memoryview next Note that exec, next and print are considered statements in Python25 """
Last edited by vegaseat; Aug 15th, 2009 at 7:32 pm.
May 'the Google' be with you!
Have you ever wondered what 'self' is doing when you use Python classes? Here is the short and sweet of it:
python Syntax (Toggle Plain Text)
# role of self in Python classes # self can be named different, but 'self' is convention class Snake(object): def __init__(self, name): # self keeps track of each instance # and also makes self.name global to class methods self.name = name # for test only print(self) def isnice(self): # a class method has self as the first argument return self.name + " is very nice" # create 2 instances of class Snake bob = Snake('Bob Python') mary = Snake('Mary Rattle') print('-'*40) # now you can get the name that has been assigned to self.name print(bob.name) print(mary.name) # access the class method print(mary.isnice()) """my result (Python 3.1.1) --> # self for each instance has a different location in memory <__main__.Snake object at 0x01E0B2B0> <__main__.Snake object at 0x01E0B090> ---------------------------------------- Bob Python Mary Rattle Mary Rattle is very nice """
drink her pretty
Sometimes it's nice to have static variable in a function. A static variable remembers its last value. Here is one way to do it with Python:
For instance, if you put
ww.x += 1
into a function, ww.x keeps track of how many times the functions has been called.
python Syntax (Toggle Plain Text)
# a class can give all global variables a save namespace # also behaves like a static variable in a function class Global(object): """ declare all global variables here """ x = 0 z = False # now all global variables can have the class instance # as a namespace, use something simple like ww ww = Global() # testing ... print( ww.x ) # 0 print( ww.z ) # False def incr_wwx() : """ ww.x does not need to be declared global and functions as a static variable here """ ww.x += 1 return ww.x print( incr_wwx() ) # 1 print( incr_wwx() ) # 2 print( incr_wwx() ) # 3 print( ww.x ) # 3 print( '-'*10) def toggle(): """ toggle between True and False on each call """ ww.z = not ww.z return ww.z print( toggle() ) # True print( toggle() ) # False print( toggle() ) # True print( ww.z ) # True
ww.x += 1
into a function, ww.x keeps track of how many times the functions has been called.
Last edited by Ene Uran; Sep 5th, 2009 at 12:12 pm.
drink her pretty
Another classical way to have a static variable in a function in python is to add this variable as an attribute of the function:
python Syntax (Toggle Plain Text)
def countcalls(): countcalls.counter += 1 print("countcalls was called %d time(s)" % countcalls.counter) countcalls.counter = 0 for i in range(5): countcalls() """ my output --> countcalls was called 1 time(s) countcalls was called 2 time(s) countcalls was called 3 time(s) countcalls was called 4 time(s) countcalls was called 5 time(s) """
![]() |
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 |
abrupt alarm ansi anti apache approximation array assignment backend beginner binary bluetooth builtin calculator character cmd converter countpasswordentry curved customdialog cx-freeze dan08 data decimals dictionary directory exe file float format function gnu halp heads homework http ideas inches input itunes java leftmouse library line lines linux list lists loop module mouse mysqlquery number numbers numeric output parsing path phonebook pointer prime programming push py2exe pygame python random recursion redirect schedule screensaverloopinactive script scrolledtext software sqlite ssh statictext statistics string strings sudokusolver terminal text thread time tlapse tuple twoup ubuntu unicode urllib urllib2 variable ventrilo webservice wikipedia wordgame write wxpython xlib






