How to Create Multi-Dimensional Array from a List

How to create a multidimensional array from lists with NumPy?

One way is to use column_stack:

>>> np.column_stack((a, b))
array([[ 1, 6],
[ 2, 7],
[ 3, 8],
[ 4, 9],
[ 5, 10]])

column_stack coerces the lists to arrays first and returns an array.

Since a and b are both a list of lists of a single element, each becomes a 2D column vector when coerced to an array. Because of this fact, you could also use hstack or concatenate to achieve the same thing (they also coerce the lists to arrays that have the correct shape for what we want). Use np.hstack((a, b)) or np.concatenate((a, b), axis=1).

For completeness, it's also possible to use np.c_ by writing np.c_[a, b]. The other methods are more direct and possibly faster though.

Python create multi dimensional array of of normal array

If you really want to work with lists, you dont need a column indexer. You can simply append the value to the correct list.


multi_arr = [[]] # start with a nested list, since your vector doesnt start with a 0
endi = len(arr)
i = 0 #row

for h in range(endi):

if arr[h] != 0:
multi_arr[i].append(arr[h])
else:
i += 1
multi_arr.insert(i,[]) # open new list

output:

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

How to define a two-dimensional array?

You're technically trying to index an uninitialized array. You have to first initialize the outer list with lists before adding items; Python calls this
"list comprehension".

# Creates a list containing 5 lists, each of 8 items, all set to 0
w, h = 8, 5
Matrix = [[0 for x in range(w)] for y in range(h)]

#You can now add items to the list:

Matrix[0][0] = 1
Matrix[6][0] = 3 # error! range...
Matrix[0][6] = 3 # valid

Note that the matrix is "y" address major, in other words, the "y index" comes before the "x index".

print Matrix[0][0] # prints 1
x, y = 0, 6
print Matrix[x][y] # prints 3; be careful with indexing!

Although you can name them as you wish, I look at it this way to avoid some confusion that could arise with the indexing, if you use "x" for both the inner and outer lists, and want a non-square Matrix.

How can I convert a list to a multi-dimensional array?

No. In fact, these aren't necessarily compatible arrays.

[,] defines a multidimensional array. List<List<T>> would correspond more to a jagged array ( object[][] ).

The problem is that, with your original object, each List<object> contained in the list of lists can have a different number of objects. You would need to make a multidimensional array of the largest length of the internal list, and pad with null values or something along those lines to make it match.

Python: How to add a list to a named multidimensional arrays

Whenever you want to retrieve an item from a data structure using a string as a keyword (e.g. "Landmarks"), a dictionary is what you're looking for.

To have the "multidimensional" functionality of points["Landmarks"]["Latitude"], you will have to have a dictionary inside another dictionary:

points = {'Landmarks': {'Latitude': lat_array, 'Longitude': lon_array}}

You can also use a deafaultdict, which supports nested dictionaries:

from collections import deafaultdict
points = defaultdict(dict)
points["Landmarks"]["Latitude"] = lat_array
points["Landmarks"]["Longitude"] = lon_array

You can see more about nested dictionaries here.

How to create multi-dimensional array from a list?

Some very simple recursion to build a tree structure:

function buildTree(array $data, $parent = null) {
$branch = array();

foreach ($data as $row) {
if ($row['parent_id'] == $parent) {
$row['children'] = buildTree($data, $row['id']);
$branch[] = $row;
}
}

return $branch;
}

$tree = buildTree($rowsFromDatabase);

Having an explicit 'children' key is usually preferable to the structure you're proposing, but feel free to modify as needed.

How to create dynamic multidimensional list in python

In your example, x is a list containing three elements (integers).
With append, you add a new element. By appending y, you are adding a list as a fourth element (3 integers, one list).

If you want to create a list of lists, tread x and y as elements for that, and combine them in a list:

x = [1,2,3]
y = [4,5,6]
list_of_lists = [x,y]

list_of_lists will then be [[1, 2, 3], [4, 5, 6]].

You can add another list by appending them:

list_of_lists.append([7,8,9])

... which will result in list_of_lists being [[1, 2, 3], [4, 5, 6], [7, 8, 9]].

How to convert list of arrays into a multidimensional array

I don't believe there's anything built into the framework to do this - even Array.Copy fails in this case. However, it's easy to write the code to do it by looping:

using System;
using System.Collections.Generic;

class Test
{
static void Main()
{
List<int[]> list = new List<int[]>
{
new[] { 1, 2, 3 },
new[] { 4, 5, 6 },
};

int[,] array = CreateRectangularArray(list);
foreach (int x in array)
{
Console.WriteLine(x); // 1, 2, 3, 4, 5, 6
}
Console.WriteLine(array[1, 2]); // 6
}

static T[,] CreateRectangularArray<T>(IList<T[]> arrays)
{
// TODO: Validation and special-casing for arrays.Count == 0
int minorLength = arrays[0].Length;
T[,] ret = new T[arrays.Count, minorLength];
for (int i = 0; i < arrays.Count; i++)
{
var array = arrays[i];
if (array.Length != minorLength)
{
throw new ArgumentException
("All arrays must be the same length");
}
for (int j = 0; j < minorLength; j++)
{
ret[i, j] = array[j];
}
}
return ret;
}

}

How can I transform a List of List (multidimensional List) to an Array of Array(multidimensional Array)?

There's no out-of-the-box method, but it's fairly straightforward to do by hand:

// Create the outer dimension of the array, with the same size as the total list
String[][] mergedArray = new String[mergedList.size()][];

// Now iterate over each nested list and convert them into the String[]
// instances that form the inner dimension
for (int i = 0; i < mergedList.size(); i++) {
mergedArray[i] = mergedList.get(i).toArray(new String[0]);
}

A slightly more efficient version of the loop body would be

List<String> innerList = mergedList.get(i);
String[] innerAsArray = innerList.toArray(new String[innerList.size()]);
mergedArray[i] = innerAsArray;

as this avoids the array resizing that would be required in my initial example (the new String[0] isn't large enough to hold the list elements). But quite frankly, unless this was a performance critical loop, I'd prefer the first version as I find it slightly clearer to see what's going on.

How to create an 2D ArrayList in java?

I want to create a 2D array that each cell is an ArrayList!

If you want to create a 2D array of ArrayList.Then you can do this :

ArrayList[][] table = new ArrayList[10][10];
table[0][0] = new ArrayList(); // add another ArrayList object to [0,0]
table[0][0].add(); // add object to that ArrayList


Related Topics



Leave a reply



Submit