简体   繁体   中英

2D arrays in Python

What's the best way to create 2D arrays in Python?

What I want is want is to store values like this:

X , Y , Z

so that I access data like X[2],Y[2],Z[2] or X[n],Y[n],Z[n] where n is variable. I don't know in the beginning how big n would be so I would like to append values at the end.

>>> a = []

>>> for i in xrange(3):
...     a.append([])
...     for j in xrange(3):
...             a[i].append(i+j)
...
>>> a
[[0, 1, 2], [1, 2, 3], [2, 3, 4]]
>>>

Depending what you're doing, you may not really have a 2-D array.

80% of the time you have simple list of "row-like objects", which might be proper sequences.

myArray = [ ('pi',3.14159,'r',2), ('e',2.71828,'theta',.5) ]

myArray[0][1] == 3.14159
myArray[1][1] == 2.71828

More often, they're instances of a class or a dictionary or a set or something more interesting that you didn't have in your previous languages.

myArray = [ {'pi':3.1415925,'r':2}, {'e':2.71828,'theta':.5} ]

20% of the time you have a dictionary, keyed by a pair

myArray = { (2009,'aug'):(some,tuple,of,values), (2009,'sep'):(some,other,tuple) }

Rarely, will you actually need a matrix.

You have a large, large number of collection classes in Python. Odds are good that you have something more interesting than a matrix.

In Python one would usually use lists for this purpose. Lists can be nested arbitrarily, thus allowing the creation of a 2D array. Not every sublist needs to be the same size, so that solves your other problem. Have a look at the examples I linked to.

If you want to do some serious work with arrays then you should use the numpy library . This will allow you for example to do vector addition and matrix multiplication, and for large arrays it is much faster than Python lists.

However, numpy requires that the size is predefined. Of course you can also store numpy arrays in a list, like:

import numpy as np
vec_list = [np.zeros((3,)) for _ in range(10)]
vec_list.append(np.array([1,2,3]))
vec_sum = vec_list[0] + vec_list[1]  # possible because we use numpy
print vec_list[10][2]  # prints 3

But since your numpy arrays are pretty small I guess there is some overhead compared to using a tuple. It all depends on your priorities.

See also this other question , which is pretty similar (apart from the variable size).

I would suggest that you use a dictionary like so:

arr = {}

arr[1] = (1, 2, 4)
arr[18] = (3, 4, 5)

print(arr[1])
>>> (1, 2, 4)

If you're not sure an entry is defined in the dictionary, you'll need a validation mechanism when calling "arr[x]", eg try-except.

If you are concerned about memory footprint, the Python standard library contains the array module ; these arrays contain elements of the same type.

Please consider the follwing codes:

from numpy import zeros
scores = zeros((len(chain1),len(chain2)), float)
x=list()
def enter(n):
    y=list()
    for i in  range(0,n):
        y.append(int(input("Enter ")))
    return y
for i in range(0,2):
    x.insert(i,enter(2))
print (x)

here i made function to create 1-D array and inserted into another array as a array member. multiple 1-d array inside a an array, as the value of n and i changes u create multi dimensional arrays

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM