Create a two-dimensional array at runtime: Difference between revisions
Content added Content deleted
No edit summary |
|||
Line 361: | Line 361: | ||
{{works with|Python| 2.5}} |
{{works with|Python| 2.5}} |
||
<lang python> |
<lang python>width = int(raw_input("Width of myarray: ")) |
||
height = int(raw_input("Height of Array: ")) |
|||
myarray = [[0] * width for i in xrange(height)] |
|||
myarray[0][0] = 3.5 |
|||
print myarray[0][0]</lang> |
|||
'''Note:''' Some people may instinctively try to write myarray as [[0] * width] * height, but the * operator creates ''n'' references to [[0] * width] |
'''Note:''' Some people may instinctively try to write myarray as [[0] * width] * height, but the * operator creates ''n'' references to [[0] * width] |
||
Line 371: | Line 371: | ||
You can also use a two element tuple to index a dictionary like so: |
You can also use a two element tuple to index a dictionary like so: |
||
<lang python> |
<lang python>myarray = dict(((w,h), 0) for w in range(width) for h in range(height)) |
||
# or, in Python 3: myarray = {(w,h): 0 for w in range(width) for h in range(height)} |
|||
⚫ | |||
myarray[(0,0)] = 3.5 |
|||
⚫ | |||
=={{header|Ruby}}== |
=={{header|Ruby}}== |