how to duplicate array entries
Steven D'Aprano
steven at REMOVE.THIS.cybersource.com.au
Mon Jan 11 02:34:04 EST 2010
On Sun, 10 Jan 2010 22:21:54 -0800, Sebastian wrote:
> Hi there,
>
> I have an array x=[1,2,3]
You have a list. Python has an array type, but you have to "import array"
to use it.
> Is there an operator which I can use to get the result
> [1,1,1,2,2,2,3,3,3] ?
Not an operator, but you can do it easily with a function. Here's the
simple version:
>>> def duplicate(items, count):
... L = []
... for item in items:
... L.extend([item]*count)
... return L
...
>>> duplicate([1,2,3], 3)
[1, 1, 1, 2, 2, 2, 3, 3, 3]
Here's a version which is short and simple enough to use in-line, but
will be slow for large lists:
>>> x = [1,2,3]
>>> count = 3
>>> sum([[item]*count for item in x], [])
[1, 1, 1, 2, 2, 2, 3, 3, 3]
Finally, here's a nasty hack that you should never, ever, ever use for
any reason except to win a bet:
>>> [locals()['_[1]'].extend([item]*(count-1)) or item for item in x]
[1, 1, 1, 2, 2, 2, 3, 3, 3]
--
Steven
More information about the Python-list
mailing list