2011/1/20 benhoyt <[email protected]>:
> Hi guys,
>
> I love the optional key to Python's sort() and max() functions, and
> I've found it handy when unique-ifying lists with web.py's
> utils.uniq() function. Very useful when you're making unique a list of
> web.storage() objects or something, for example de-duping a list of
> rows from the database based on some column or transform on a column.
>
> So here's my updated version of uniq() that handles an optional key
> (with a unit test for the key case):
>
> ----------
> def uniq(seq, key=None):
>    """Remove duplicate elements from given sequence (using key
> function to transform
>    items, if given).
>
>    >>> uniq([1, 2, 3, 1, 4, 5, 6])
>    [1, 2, 3, 4, 5, 6]
>    >>> uniq(['Foo', 'bar', 'Bar', 'FOO', 'bill'], key=str.lower)
>    ['Foo', 'bar', 'bill']
>
>    """
>    seen = set()
>    result = []
>    for item in seq:
>        if key is None:
>            item_key = item
>        else:
>            item_key = key(item)
>        if item_key in seen:
>            continue
>        seen.add(item_key)
>        result.append(item)
>    return result
> ----------

I missed that too. Implemented!

https://github.com/webpy/webpy/commit/f74d940e591ce7d1acde6cd4396e05f3c15a167b

> Yes, I know, I don't have to test "key is None" each time around the
> loop. However, I figured that a test against None would be
> significantly faster that calling a (no-op) function each time around
> the loop.

Readability counts.

> Also, I noticed when running the unit tests for utils.py that
> datestr() fails, because "%e" isn't a valid strftime formatting
> operator. It's not in the documentation () -- perhaps it's a Linux-
> only thing?

Do you mean the doctests?

-- 
You received this message because you are subscribed to the Google Groups 
"web.py" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/webpy?hl=en.

Reply via email to