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):
# 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'] """
# 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] """
# 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.)
# 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 """
# 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)
# 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} ] """
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
# 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))
# 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)
# 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 """
# 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 """
# 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
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) """
| DaniWeb Message | |
| Cancel Changes | |