newbie:unique problem
Heiko Wundram
modelnine at ceosg.de
Fri Mar 18 01:27:10 EST 2005
On Thursday 17 March 2005 23:31, Brian van den Broek wrote:
> Am I not
> right in thinking that with the dict approach there is no guarantee
> that the order from the original list will be preserved?
Yup, absolutely right that the original ordering will not be preserved. But, I
wonder whether this actually matters, when the op is actually using these
strings as a sort of set (to check whether someone belongs to some group, if
I understand him correctly).
> Also, Heiko, I wonder what is the reason for reversed(oldlist)? Since
> the list isn't being mutated, there isn't any danger in forward
> iteration over it. (Plus, unless I'm mistaken, its the only thing
> making yours a 2.4-only solution.)
The reason for walking the list backwards is easily demonstrated by the
following two runs:
>>> def uniqueItems(oldlist,comppos=3):
... rv = {}
... for i in reversed(oldlist):
... rv[i[:comppos]] = i
... return rv.values()
...
>>> def uniqueItemsWithoutRev(oldlist,comppos=3):
... rv = {}
... for i in oldlist:
... rv[i[:comppos]] = i
... return rv.values()
...
>>> uniqueItems(["AAA BC","BBB KK","CCC TD","AAA KP","CCC TD"])
['AAA BC', 'BBB KK', 'CCC TD']
>>> uniqueItemsWithoutRev(["AAA BC","BBB KK","CCC TD","AAA KP","CCC TD"])
['AAA KP', 'BBB KK', 'CCC TD']
When you walk the list forwards, the item that gets returned for the
corresponding "key" is the item that is last found (as I don't check whether
the item is already in the dict in the loop, but always just set), when you
walk the list backwards, the item that is last found backwards (thus farthest
in front) is returned.
In case this doesn't matter (well, I guess it actually doesn't, as the OP only
needs the first n chars, that's the reason for this function), you can easily
leave out the reversed() and remove the constraint on Python 2.4. If you must
have it in this order, and still use Python <2.4, you'd need to use something
like oldlist[::-1], which will copy the list. reversed(list) does an
optimization.
HTH!
--
--- Heiko.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20050318/8d1968d2/attachment.sig>
More information about the Python-list
mailing list