Convert from numbers to letters

Peter Otten __peter__ at web.de
Thu May 19 16:18:00 EDT 2005


Bill Mill wrote:

>> By the way, sorted() can be removed from your original post.
>> 
>> Code has no effect :-)
> 
> I'm gonna go ahead and disagree with you:
> 
>>>> sorted([''.join((x, y)) for x in alpha \
> ...    for y in [''] + [z for z in alpha]], key=len) == \
> ... [''.join((x,y)) for x in alpha for y in [''] + [z for z in alpha]]
> False
> 

That's not your original code. You used the contents to modify the locals()
(effectively globals()) dictionary:

>>>> alpha = 'abcdefghijklmnopqrstuvwxyz'
>>>> for i, digraph in enumerate(sorted([''.join((x, y)) for x in alpha \
> for y in [''] + [z for z in alpha]], key=len)):
> ...     locals()[digraph] = i + i
> ...
> 

Of course you lose the order in that process. 
When you do care about order, I suggest that you swap the for clauses
instead of sorting, e. g:

>>> alpha = list("abc")
>>> items = [x + y for x in [""] + alpha for y in alpha]
>>> items == sorted(items, key=len)
True

Peter
 



More information about the Python-list mailing list