How To Number A 2 Dimensional List?
I have these lists inside a list that I am trying to number. I also have two variables, row and column, which are taken as input. lst = row*[column*[0]] This makes lists inside a
Solution 1:
I think this would be the most "pythonic" way:
from pprint import pprint
rows=6
cols =10
lst = [[(j*cols+i) for i inrange(1,cols+1)] for j inrange(rows)]
pprint(lst)
Output:
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
[21, 22, 23, 24, 25, 26, 27, 28, 29, 30],
[31, 32, 33, 34, 35, 36, 37, 38, 39, 40],
[41, 42, 43, 44, 45, 46, 47, 48, 49, 50],
[51, 52, 53, 54, 55, 56, 57, 58, 59, 60]]
Solution 2:
The quick and dirty solution would be:
lst = []
for r inrange(row):
lst.append([])
for c inrange(column):
lst[r].append(c + r *column)
This can be implemented more cleanly using numpy and reshaping like:
lst = numpy.arange(row*column).reshape(row, column).tolist()
Solution 3:
Try this:
l = []
for i in range(0, 6):
row = []
for j in range(1,11):
row.append(i*10+j)
l.append(row)
l
>>>[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
[11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
[21, 22, 23, 24, 25, 26, 27, 28, 29, 30],
[31, 32, 33, 34, 35, 36, 37, 38, 39, 40],
[41, 42, 43, 44, 45, 46, 47, 48, 49, 50],
[51, 52, 53, 54, 55, 56, 57, 58, 59, 60]]
Solution 4:
You can get this using zip
and range
.
list(zip(*[iter(range(1, row*column+1))]*column))
This results in a list of tuples but if you need a list of lists, just map
list
to zip
list(map(list, zip(*[iter(range(1, row*column+1))]*column)))
Results:
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 11, 12, 13, 14, 15, 16, 17, 18, 19], [20, 21, 22, 23, 24, 25, 26, 27, 28, 29], [30, 31, 32, 33, 34, 35, 36, 37, 38, 39], [40, 41, 42, 43, 44, 45, 46, 47, 48, 49], [50, 51, 52, 53, 54, 55, 56, 57, 58, 59]]
Solution 5:
Why not using list comprehension as follows:
lst = [[(i+j*column)+1for i inrange(column)] for j inrange(row)]
Post a Comment for "How To Number A 2 Dimensional List?"