# 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"
<http://stackoverflow.com/questions/260056/hashtable-dictionary-map-lookup-with-regular-expressions>
>>> 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: Whats the most efficient/cleanest way to order that list by weight then factor (numericaly). The resulting list should look like: |
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 lambda, go for
http://stackoverflow.com/questions/134626/which-is-more-preferable-to-use-in-python-lambda-functions-or-nested-functions discuses when you should use lambdas
♥ ¸¸.•*¨*•♫♪♪♫•*¨*•.¸¸♥
No comments:
Post a Comment