On 28/03/16 22:25, Chris Angelico wrote:
Just out of interest, did you (generic you) happen to notice Mark's
suggestion? It's a one-liner that nicely expresses the intention and
accomplishes the goal:
yy = [aa for aa in xx for _ in range(nrep)]
It quietly went through without fanfare, but I would say this is the
perfect solution to the original problem.
I noticed it (and I timed it - it was ~30% faster than my version
(because mine was creating short transient list objects), but it takes a
_LOT_ - millions - of iterations of the example case (nrep = 3, xx =
two-element-list) to even make it measurable on my PC). It would have
probably been even quicker if he'd cached the range() object.
I'm not convinced it's particularly intuitive, though. That trailing
"for _ in range(nrep)" looks at first glance like an error - some code
that's generating a value that is not referenced anywhere else.
It makes perfect sense when one analyses it, but it's not the most
immediately grokkable construct.
Hmmm. It's almost as if in this instance I'd prefer something like:
yy = [for aa in xx for _ in range(nrep): aa]
But I know we can't go /there/ ;)
E.
--
https://mail.python.org/mailman/listinfo/python-list