Reputation: 3350
Starting with a list of tuples which represent points on a surface.
list = [(48, 228), (96, 204), (120, 192), ... ]
What is the pythonic way to create a new list, so we can call values from the original list, as if they were distributed on a grid?
Like this:
>>>print grid[0][0]
(48, 228)
>>>print grid[0][1]
(96, 204)
Upvotes: 1
Views: 179
Reputation: 5114
This is a list comprehension that solves it:
l = [(48, 228), (96, 204), (120, 192), ... ]
# 'width' is the width of your bidimensional table (grid)
bidimensional = [l[a*width:(a+1)*width] for a in xrange(len(l)/width)]
Explained:
[ # make a list of:
l[a*width:(a+1)*width]
# get the 'a'-th slice of length 'width' of the initial list
for a in xrange(len(l)/width) # for 'len(l)/width' slices
]
Test:
>>> l = [(1, 11), (2, 22), (3, 33), (4, 44), (5, 55), (6, 66),(7, 77), (8, 88)]
>>> width = 2
>>> bidimensional = [l[a*width:(a+1)*width] for a in xrange(len(l)/width)]
>>> bidimensional
[[(1, 11), (2, 22)], [(3, 33), (4, 44)], [(5, 55), (6, 66)], [(7, 77), (8, 88)]]
>>> bidimensional[2][1]
(6, 66)
Upvotes: 0
Reputation: 12765
I don't really see the difficulty, maybe a simple grid=[list]
would suffice.
If you want to have it as a fast 2d-array, use numpy:
import numpy as np
grid = np.array(list).reshape(1,-1)
print grid[0,1] #prints (96, 204)
If your data become larger or higher dimensional, always use numpy arrays, don't use lists-of-lists.
One remark: please don't call your variable list
, it will hide the built-in method list
.
Upvotes: 1