Closures in leu of pointers?
Tim Chase
tim at thechases.com
Sat Jun 29 15:42:58 EDT 2013
On 2013-06-29 19:19, Steven D'Aprano wrote:
> Nobody ever asks why Python doesn't let you sort an int, or take
> the square of a list...
just to be ornery, you can sort an int:
>>> i = 314159265
>>> ''.join(sorted(str(i)))
'112345569'
And I suppose, depending on how you define it, you can square a list:
>>> lst = list('abcd')
>>> import itertools
>>> list(itertools.product(lst, lst))
[('a', 'a'), ('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'a'), ('b',
'b'), ('b', 'c'), ('b', 'd'), ('c', 'a'), ('c', 'b'), ('c', 'c'),
('c', 'd'), ('d', 'a'), ('d', 'b'), ('d', 'c'), ('d', 'd')]
Or, if you want to do it frequently, Python graciously even allows
you to do things like
>>> class MultiList(list):
... def __pow__(self, power):
... return list(itertools.product(*([self] * power)))
...
>>> lst = MultiList("abcd")
>>> lst ** 2
[('a', 'a'), ('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'a'), ('b',
'b'), ('b', 'c'), ('b', 'd'), ('c', 'a'), ('c', 'b'), ('c', 'c'),
('c', 'd'), ('d', 'a'), ('d', 'b'), ('d', 'c'), ('d', 'd')]
:-)
-tkc
More information about the Python-list
mailing list