简体   繁体   English

Python中二维数组的替代方法

[英]Alternative to bidimensional array in Python

I need a array of n elements, in which each element has 2 attributes. 我需要一个n元素的数组,其中每个元素都有2个属性。

A.element[0].name="qwe"
A.element[0].age=23
A.element[1].name="www"
A.element[1].age=24
...
A.element[n].name="e"
A.element[n].age=25

Is there another form which doesn't involve designing a class? 还有另一种不涉及设计课程的形式吗?

There is collections.namedtuple . collections.namedtuple

>>> from collections import namedtuple
>>> Element = namedtuple('Element', 'name age')
>>> A.element[0] = Element('qwe', 23)
>>> print A.element[0].name
qwe
>>> print A.element[0].age
23

However these are tuples, not lists, and so they can't be changed. 但是,这些是元组,而不是列表,因此无法更改。 Also, these are still essentially classes, but you just don't define them with the class keyword. 同样,这些本质上仍然是类,但是您不必使用class关键字定义它们。 See this for an in-depth explanation. 请参阅此内容以获取详细说明。

You can use an array of dictionaries. 您可以使用字典数组。

Something like this: 像这样:

A = [
    {'name': 'qwe', 'age': 23},
    {'name': 'www', 'age': 24}
]

You can simplify inserting by doing something like this: 您可以通过执行以下操作来简化插入操作:

A = []

def addPerson(name, age):
    global A
    A.append({'name': name, 'age': age})

Or just make the dictionaries into arrays, so you do not have to specify 'name' and 'age' in every line. 或者只是将字典分成数组,因此您不必在每一行中都指定“名称”和“年龄”。 It might be easier writing a class representing a person (or whatever it is). 编写代表一个人(或任何人)的类可能会更容易。

If you use numpy, you can also use structure array: 如果使用numpy,则还可以使用结构数组:

In [66]: struct = np.dtype([("name", np.object), ("age", np.int)])
a = np.array([("abc", 12), ("def", 20), ("xyz", 50)], dtype=struct)
a[0]
Out[66]: ('abc', 12)

In [67]: a[0]["name"]
Out[67]: 'abc'

In [68]: a["name"]
Out[68]: array([abc, def, xyz], dtype=object)

In [69]: a["age"]
Out[69]: array([12, 20, 50])

In [72]: a["age"][2]
Out[72]: 50

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

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