This works but is unwieldy and not very 'Pythonic'. I'd also like to be able to run through different values for 'numValues', say 4 to 40...
innerList = []
outerList = []
numValues = 12
loopIter = 0
for i in range(numValues):
innerList.append(0)
for i in range(numValues):
copyInnerList = innerList.copy()
outerList.append(copyInnerList)
for i in range(len(innerList)):
for j in range(loopIter + 1):
outerList[i][j] = 1
loopIter += 1
print(outerList)
The task is to convert a nested list into a single list in python i.e no matter how many levels of nesting is there in the python list, all the nested have to be removed in order to convert it to a single containing all the values of all the lists inside the outermost brackets but without any brackets inside.
In Python, we can create a list by surrounding all the elements with square brackets [] and each element separated by commas. It can be used to store integer, float, string and more.
When you want to insert an item at a specific position in a nested list, use insert() method. You can merge one list into another by using extend() method. If you know the index of the item you want, you can use pop() method. It modifies the list and returns the removed item.
numValues = 12
result = [ [1] * i + [0] * (numValues - i) for i in range(1, numValues+1) ]
You can do this as a nested list comprehension, with two iterators over range(numValues)
and only setting a 1
when the second iterator is <=
the first:
numValues = 4
outerList = [[1 if j <= i else 0 for j in range(numValues)] for i in range(numValues)]
print(outerList)
Output:
[[1, 0, 0, 0], [1, 1, 0, 0], [1, 1, 1, 0], [1, 1, 1, 1]]
If numpy is an option, this can be done very easily with np.tril
:
import numpy as np
n=5
out = np.ones((n,n))
np.tril(out)
array([[1., 0., 0., 0., 0.],
[1., 1., 0., 0., 0.],
[1., 1., 1., 0., 0.],
[1., 1., 1., 1., 0.],
[1., 1., 1., 1., 1.]])
I think it is a little bit more intuitive using a matrix approach with numpy.
numValues = 5
my_array = np.eye(numValues)
it results in
array([[1., 0., 0., 0., 0.],
[0., 1., 0., 0., 0.],
[0., 0., 1., 0., 0.],
[0., 0., 0., 1., 0.],
[0., 0., 0., 0., 1.]])
From this matrix you can see that the only think you need to do is to sum the rows
sol = [np.sum(mat[:i], axis=0) for i in range(numValues+1)][1:]
and you get
[array([1., 0., 0., 0., 0.]),
array([1., 1., 0., 0., 0.]),
array([1., 1., 1., 0., 0.]),
array([1., 1., 1., 1., 0.]),
array([1., 1., 1., 1., 1.])]
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