Python - What data structure to use?

I have a large array of numeric data that I need to sort, insert and move values ​​back and forth in sorted order. I used to use a simple array. Now each value should be associated with an identifier (a unique int, just for the ride).

Is it possible to extend an array class, or do I need to use a list of tuples? What is my best option?

+5
source share
4 answers

You can simply use a list to have a sorted list. If you want to link additional data, you can either use a tuple to store data, or even create a custom object for it that stores the identifier in an additional field.

You do not need to expand the list for this, you can just put any object in the list. For example, this would be easily possible:

>>> lst = [ ( 132, 'foobar' ), ( 58, 'other value' ) ]
>>> lst.append( ( 70, 'some data value' ) )
>>> lst
[(132, 'foobar'), (58, 'other value'), (70, 'some data value')]
>>> lst.sort( key=lambda x: x[0] )
>>> lst
[(58, 'other value'), (70, 'some data value'), (132, 'foobar')]
>>> lst.sort( key=lambda x: x[1] )
>>> lst
[(132, 'foobar'), (58, 'other value'), (70, 'some data value')]

edit:

If you are using Python 3.1+, you can also use a type collections.OrderedDict. This is an extension to normal dictthat maintains order as it does list.

+3
source

, - O (n), .

blist, - API, O (lg N).

+2

, , .

, , :

a = {'key':'id'}

keys = a.keys()

keys.sort()

for k in keys:

    print a[key]
+1

poke, 2d, , NumPy, , Python. 2D-,

[ [1  614.124]
  [2  621236.139]
  [3  1243.612] ]

.sort().

+1

All Articles