简体   繁体   English

Python中的2D数组

[英]2D arrays in Python

What's the best way to create 2D arrays in Python? 在Python中创建2D数组的最佳方法是什么?

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. 这样我就可以访问X[2],Y[2],Z[2]X[n],Y[n],Z[n] ,其中n是可变的。 I don't know in the beginning how big n would be so I would like to append values at the end. 我没有在一开始知道有多大n会,所以我想在最后追加值。

>>> 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. 80%的时候你有简单的“行状对象”列表,这可能是正确的序列。

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 20%的时间你有一本字典,由一对键入

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. Python中有大量的集合类。 Odds are good that you have something more interesting than a matrix. 你有比矩阵更有趣的东西是好的。

In Python one would usually use lists for this purpose. 在Python中,通常会使用列表来实现此目的。 Lists can be nested arbitrarily, thus allowing the creation of a 2D array. 列表可以任意嵌套,从而允许创建2D数组。 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 . 如果你想对数组做一些认真的工作,那么你应该使用numpy库 This will allow you for example to do vector addition and matrix multiplication, and for large arrays it is much faster than Python lists. 这将允许您进行矢量加法和矩阵乘法,对于大型数组,它比Python列表快得多。

However, numpy requires that the size is predefined. 但是,numpy要求大小是预定义的。 Of course you can also store numpy arrays in a list, like: 当然,您也可以将numpy数组存储在列表中,例如:

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. 但是由于你的numpy数组非常小,我想与使用元组相比有一些开销。 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. 如果您不确定字典中是否定义了条目,则在调用“arr [x]”时需要验证机制,例如try-except。

If you are concerned about memory footprint, the Python standard library contains the array module ; 如果您担心内存占用,Python标准库包含数组模块 ; 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 一个数组内的多个1-d数组,当n和i的值改变时,你创建了多维数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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