Using only list comprehensions
Here is one way you can do this using enumerate
. The logic is as below -
- Iterate over each element of the myLIST with enumerate to get their index position.
- If position is greater than 0th index, return the specific element along with a list of 0s
- Else, return the complete list when index is 0.
[[myLIST[i]]+([0]*(len(myLIST)-1)) if i>0 else myLIST for i,j in enumerate(myLIST)]
[[41, 32, 49, 4, 55],
[32, 0, 0, 0, 0],
[49, 0, 0, 0, 0],
[4, 0, 0, 0, 0],
[55, 0, 0, 0, 0]]
Since your goal is to master list comprehensions, I would recommend the following guides that I found useful long back with the same -
- https://www.programiz.com/python-programming/list-comprehension
- https://www.analyticsvidhya.com/blog/2021/06/10-examples-you-should-try-to-master-list-comprehensions-in-python/
Using a combination of numpy and list comprehension
For completeness, you can do this purely in numpy by using stride_tricks
or np.roll
as well.
Check this - Roll rows of a matrix independently
Another approach is to use a combination of np.roll
and list comprehension with ternary operator conditions on the index -
- Convert myLIST to a diagonal matrix using
np.diag(myLIST)
array([[41, 0, 0, 0, 0],
[ 0, 32, 0, 0, 0],
[ 0, 0, 49, 0, 0],
[ 0, 0, 0, 4, 0],
[ 0, 0, 0, 0, 55]])
Next, you can then np.roll
each of the of the rows in the array independently by the index number * -1. So, for [ 0, 0, 49, 0, 0]
, -2 roll would result in [ 49, 0, 0, 0, 0]
Put a condition to roll every thing with index > 0 and when index is 0, just return the original array.
Here is the complete code as a list comprehension -
import numpy
arr = np.diag(myLIST)
[list(np.roll(j,-1*i)) if i>0 else myLIST for i,j in enumerate(arr)]
[[41, 32, 49, 4, 55],
[32, 0, 0, 0, 0],
[49, 0, 0, 0, 0],
[4, 0, 0, 0, 0],
[55, 0, 0, 0, 0]]