Answered # Empty 2D Array

Featured Reply jlm699 320 vegaseat 1,720 bvdet 75 woooee 813 jlm699 320 Need some help with this Array. I am trying to get the sum of the even numbers and the sum of the odd numbers using a for each loop. I know the answers to what I am trying to achive are sum of even = 84 and the sum of ...

1

hoe to write a generic code for creating a empty 2D array and dynamically insert values in it.

```
>>> arr_2d = [[]]
>>> arr_2d[0].append(0)
>>> arr_2d[0].append(1)
>>> arr_2d.append([3,4,5])
>>> arr_2d
[[0, 1], [3, 4, 5]]
>>>
```

It might benefit you to create a 2d array class to handle the many different aspects of working with a 2d array.

0

Not sure if I follow this correctly, but you start with a one dimensional list and append other lists to it. For example ...

```
qq = []
for row in range(3):
for col in range(3):
qq.append([row, col])
print qq
"""
my output -->
[[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2]]
"""
```

You could use None as a placeholder.

0

I like using list comprehensions for this kind of task.

```
>>> cols = 4
>>> rows = 5
>>> array = [[0 for i in range(cols)] for j in range(rows)]
>>> array
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
>>>
```

0

If it is easier to get your head around, you can use a dictionary of lists, with the dictionary key as the row number, each containing x columns. You could also take this one step further and use a dictionary of dictionaries with row and column number as keys.

```
def populate_array(rows, columns):
array_dic = {}
for row in range(1, rows+1): ## starts with one, not zero
array_dic[row] = []
for col in range(0, columns):
array_dic[row].append('None') ## initialize to 'None'
return array_dic
if __name__ == "__main__":
rows = 10
columns = 5
ret_dic = populate_array(rows, columns)
for key in ret_dic.keys():
print key, ret_dic[key]
##--- change some value
row = 3
col = 1
ret_dic[row][col] = 'Changed'
print "\n"
for key in ret_dic.keys():
print key, ret_dic[key]
```

0

You could also take this one step further and use a dictionary of dictionaries with row and column number as keys.

Brilliant. I really like this idea! Nice!

This question has already been answered. Start a new discussion instead.

Recommended Articles

When I execute this progammatically, I get a table with row heights much larger than when I do this manually.

Note : Sel is the Word.Selection object and the Clipboard contains an Excel Table.

```
public void AddClipboard()
{
Sel.PasteExcelTable(false,false, false);
var t = Sel.Tables[Sel.Tables.Count];
t.AutoFitBehavior(Word.WdAutoFitBehavior.wdAutoFitContent);
}
```

the function that I created to find the ...