Welcome, guest | Sign In | My Account | Store | Cart

This simple code act like conditional operator "?:" (or ternary) operator, which operates as in C and many other languages, but more readable.

Similar to Oracle's decode function but can return any value :-)

Python, 22 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
def decode(*arguments):
    """Compares first item to subsequent item one by one.

    If first item is equal to a key, returns the corresponding value (next item).
    If no match is found, returns None, or, if default is omitted, returns None.
    """
    if len(arguments) < 3:
        raise TypeError, 'decode() takes at least 3 arguments (%d given)' % (len(arguments))
    dict = list(arguments[1:])
    if arguments[0] in dict:
        index = dict.index(arguments[0]);
        if index % 2 == 0 and len(dict) > index+1:
            return dict[index+1]
        return dict[-1]
    elif len(dict) % 2 != 0:
        return dict[-1]

# example usage
return_value = decode('b', 'a', 1, 'b', 2, 3)

var = 'list'
return_type = decode(var, 'tuple', (), 'dict', {}, 'list', [], 'string', '')

2 comments

Arthur Lee 20 years, 3 months ago  # | flag

A bit more pythonic. How about making it slightly more interesting?

def decode(*arguments):
    """Use the first argument to select one of the subsequent item.

    First argument is any value.  Subsequent argument must be sequence
    type with minimum of 2 items.  One of the subsequent argument will
    be selected when its first item is equal to the first argument.
    The second and subsequent item in the selected argument will
    be returned.

    """
    if len(arguments) < 2:
        raise TypeError, 'decode() takes at least 2 arguments (%d given)' % (len(arguments))
    arg = arguments[0]
    for item in arguments[1:]:
        if arg == item[0]: return item[1:]



# Example
print decode('b', ('a', 1), ('b', 2))
print decode('a', 'aGood Morning', 'pGood Evening')

var='list'
print decode(var, ['tuple', ()], ['dict', {}], ['list', []], ['string', ''])
Chris Arndt 18 years ago  # | flag

decode.py. As my pre-poster suggested:

def decode(sel, *seq):
    for s in seq:
        if sel == s[0]:
            return s[1:]
            break

def ternary(cond, a, b):
    """If `cond` evaluates to True, return `a`, otherwise `b`."""

    return decode(cond, (True, a), (False, b))[0]
Created by Goh S H on Thu, 30 Aug 2001 (PSF)
Python recipes (4591)
Goh S H's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks