On Mon, Nov 11, 2013 at 9:09 PM, <lorenzo.ga...@gmail.com> wrote: > Regarding the "select" statement, I think the most "Pythonic" approach is > using dictionaries rather than nested ifs. > Supposing we want to decode abbreviated day names ("mon") to full names > ("Monday"):
That's an obvious mapping, though. If you're using a select/switch statement to handle straight-forward one-to-one mappings, then yes, obviously the better way to do it is to use a dictionary. In the more general sense, a switch/case block is much more directly translated into if/elif/else statements. You can't, for instance, build up a dictionary that handles inequalities, but you can do that with elif. That is, normally you can't. I have occasionally built up mappings that handle inequalities - it's a form of denormalization. Consider the following logic: A 'minor weapon' is based on a roll of a 100-sided dice. If it's 01 to 70, "+1 weapon: 2,000gp [weapon]"; if it's 71 to 85, "+2 weapon: 8,000gp [weapon]"; if 86 to 90, "Specific weapon [minor specific weapon]"; and if 91 to 100, "Special ability [minor special weapon] and roll again". My code to handle that starts out with this array: "minor weapon":({ 70,"+1 weapon: 2,000gp [weapon]", 85,"+2 weapon: 8,000gp [weapon]", 90,"Specific weapon [minor specific weapon]", 100,"Special ability [minor special weapon] and roll again", }), (that's Pike; in Python it'd be a list, or maybe a tuple of tuples), and denormalizes it into a lookup table by creating 70 entries quoting the first string, 15 quoting the second, 5, and 10, respectively. So, with a bit of preprocessing, a lookup table (which in this case is an array (list), but could just as easily be a dict) can be used to handle inequalities. But this is because lookup tables can be treated as data, where if/elif/else blocks have to be code; there are roughly 42 million such lookup tables in the code I snagged that from, and having code for each one would work out far less manageable. Normally, you'll want to render inequalities with code as if/elif. ChrisA -- https://mail.python.org/mailman/listinfo/python-list