If you want to create an array of a pre-defined size where each element is preset to zero the following code will work
Code: Select all
w = 60
h = 2
array = [[0 for x in range(w)] for y in range(h)] Code: Select all
w = 60
h = 2
array = [[0 for x in range(w)] for y in range(h)] Not elegant, but this is what I have tended to use ...scotty101 wrote:for defining arrays people often use numpy
Code: Select all
def Dim( size, defaultValue=0 ):
array = []
while len(array) < size:
array.append( defaultValue )
return array
oneDimensionArray = Dim(5)
print( oneDimensionArray )
Code: Select all
array = [[0] * w] * hPerhaps post your full code. You can add diagnostic print statements to show what 'h' and 'w' are, what size of arrays you have created, and what the array index 'i' is when it fails.supra wrote:And I cannot figured out of index.
Because that will create one list of w items for the first row and then references to that first row for the other rows rather than new lists for each row.jojopi wrote:What is wrong with:(Strictly speaking, none of these examples creates an array, but rather a list of lists. Arrays are not really a thing in Python unless you import a module to implement them. Lists differ from conventional arrays in that the size is not fixed, and the elements are not constrained all to have the same type.)Code: Select all
array = [[0] * w] * h
Oops; that also affects my own Dim() code given above. In my defence I have only ever used it for creating single dimension arrays, and failed to fully test the code. Thanks for highlighting the issue.Paeryn wrote:Because that will create one list of w items for the first row and then references to that first row for the other rows rather than new lists for each row.jojopi wrote:What is wrong with:...
Code: Select all
array = [[0 for _ in range(w)] for _ in range(h)]
Code: Select all
>>> x = 4
>>> array = [0 for x in range(3)]
>>> print(x) ## x will still have the original value 4
4
Code: Select all
>>> x = 4
>>> array = [0 for x in range(3)]
>>> print x ## Oops, x will now be 2 from the list comprehension
2
Code: Select all
for i in range(0, 60):
pt = [0, 0]
angle = 6.0 * i * pi / 180
for j, p in enumerate(pt):
radius = cent[0] - 25 + 20 * j
p = (int(cent[0] + radius * cos(angle)),
int(cent[1] + radius * sin(angle)))
cv2.line(clk, pt[0], pt[1], (0, 255, 0), 2, cv2.LINE_AA)
Code: Select all
for i in range(0, 60):
pt = [0, 0]
angle = 6.0 * i * pi / 180
for j in range(2):
radius = cent[0] - 25 + 20 * j
pt[j] = (int(cent[0] + radius * cos(angle)),
int(cent[1] + radius * sin(angle)))
cv2.line(clk, pt[0], pt[1], (0, 255, 0), 2, cv2.LINE_AA)