How can I make a function that will create a list, increasing the amount of numbers it contains each time to a specified value?
For example if the max was 4, the list would contain
1, 2, 2, 3, 3, 3, 4, 4, 4, 4
It's difficult to explain what I'm looking for, but from the example I think you'll understand!
Thanks
I'd use itertools.chain
:
itertools.chain(*([i] * i for i in range(1, 5)))
or itertools.chain.from_iterable
to do it slightly more lazily:
itertools.chain.from_iterable([i] * i for i in range(1, 5))
And for the ultimate laziness, pair with itertools.repeat
-- (using xrange
in you're using python2.x):
import itertools as it
it.chain.from_iterable(it.repeat(i, i) for i in range(1, 5))
As a function:
def lazy_funny_iter(n):
return it.chain.from_iterable(it.repeat(i, i) for i in range(1, n+1))
def lazy_funny_list(n):
return list(lazy_funny_iter(n))
A Nested loop. This would be a very basic way to do it. There are much better ways, this should give you the general idea.
>>> def listmaker(num):
l = []
for i in xrange(1, num+1):
for j in xrange(i):
l.append(i)
return l
>>> print listmaker(4)
[1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
Here is doing it with list comprehension:
>>> def listmaker2(num):
return [y for z in [[x]*(x) for x in xrange(1, num+1)] for y in z]
>>> print listmaker2(4)
[1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
Using extend as suggested.
>>> def listmaker3(num):
l = []
for i in xrange(1, num+1):
l.extend([i]*(i))
return l
>>> print listmaker3(4)
[1, 2, 2, 3, 3, 3, 4, 4, 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