This question will no doubt to a piece of cake for a Python 2.7 expert (or enthusiast), so here it is.
How can I create a list of integers whose value is duplicated next to it's original value like this?
a = list([0, 0, 1, 1, 2, 2, 3, 3, 4, 4])
It's really easy to do it like this:
for i in range(10): a.append(int(i / 2))
But i'd rather have it in one simple line starting a = desired output.
Thank you for taking the time to answer.
PS. none of the "Questions that may already have your answer were what I was looking for.
>>> [i//2 for i in xrange(10)]
[0, 0, 1, 1, 2, 2, 3, 3, 4, 4]
A simple generic approach:
>>> f = lambda rep, src: reduce(lambda l, e: l+rep*[e], src, [])
>>> f(2, xrange(5))
[0, 0, 1, 1, 2, 2, 3, 3, 4, 4]
>>> f(3, ['a', 'b'])
['a', 'a', 'a', 'b', 'b', 'b']
>>> sorted(2*range(5))
[0, 0, 1, 1, 2, 2, 3, 3, 4, 4]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With