1

I need a array of n elements, in which each element has 2 attributes.

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?

Jon Gauthier
  • 25,202
  • 6
  • 63
  • 69
Quarktum
  • 669
  • 1
  • 8
  • 26

3 Answers3

4

There is 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. See this for an in-depth explanation.

Community
  • 1
  • 1
Volatility
  • 31,232
  • 10
  • 80
  • 89
2

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).

EClaesson
  • 1,568
  • 2
  • 15
  • 26
1

If you use numpy, you can also use structure array:

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
HYRY
  • 94,853
  • 25
  • 187
  • 187