Welcome~~~


Another blog:
http://fun-st.blogspot.com/

It is easier to write an incorrect program than understand a correct one.

Friday, February 25, 2011

Daily Notes - Python

# The "collections" and "itertools" module in Python:

Checkout an example:

Python-org  Introduction for Collections: http://docs.python.org/library/collections.html


# Besids, a very good example for using the Regex for "hashing"
  >>> regex_dict = { re.compile(r'foo.') : 12, re.compile(r'^FileN.*$') : 35 }
>>> regex_dict['food']
12
>>> regex_dict['foot in my mouth']
12
>>> regex_dict['FileNotFoundException: file.x does not exist']
35

# Sort for dictionary tuples --- excellent example:

I've got a python list of dictionaries:

  mylist = [
{'id':0, 'weight':10, 'factor':1, 'meta':'ABC'},
{'id':1, 'weight':5, 'factor':1, 'meta':'ABC'},
{'id':2, 'weight':5, 'factor':2, 'meta':'ABC'},
{'id':3, 'weight':1, 'factor':1, 'meta':'ABC'}
]

Whats the most efficient/cleanest way to order that list by weight then factor (numericaly). The resulting list should look like:

  mylist = [
{'id':3, 'weight':1, 'factor':1, 'meta':'ABC'},
{'id':1, 'weight':5, 'factor':1, 'meta':'ABC'},
{'id':2, 'weight':5, 'factor':2, 'meta':'ABC'},
{'id':0, 'weight':10, 'factor':1, 'meta':'ABC'},

  mylist.sort(key=lambda d: (d['weight'], d['factor']))     # note: this is using the key- corresponding value to sort the dic

or

  import operator
mylist
.sort(key=operator.itemgetter('weight', 'factor'))

Below will work as well:
  def cmp_dict(x, y):
    weight_diff
= y['weight'] - x['weight']
   
if weight_diff == 0:
       
return y['factor'] - x['factor']
   
else:
       
return weight_diff

myList
.sort(cmp_dict)

# Further to understand the lambdago for 



--

♥ ¸¸.•*¨*•♫♪♪♫•*¨*•.¸¸♥

No comments:

Post a Comment