Could someone please help. I would like to sort a multidimensional array. But to sort it out by one key which appears in all array for example.

total=[[serial,'john'],[[serial,'james']]

all the records i have all in arrays they contain a "serial" i would like sort by serial.

I have used

total.sort()

this sorted that names but johns serial is the first and i would like to sort by serial not by name. Please help :S

There are number of ways, but this way I mostly use:

# sorting a list of lists by index

def sort_inner(inner):
    """
    inner is each inner list in the list of lists to be sorted
    (here item at index 1 of each inner list is to be sorted)
    """
    return inner[1]

serial = 123456
total = [[serial, 'john'], [serial, 'james']]

total.sort(key=sort_inner)
print total  # [[123456, 'james'], [123456, 'john']]

Could someone please help. I would like to sort a multidimensional array. But to sort it out by one key which appears in all array for example.

total=[[serial,'john'],[[serial,'james']]

all the records i have all in arrays they contain a "serial" i would like sort by serial.

I have used

total.sort()

this sorted that names but johns serial is the first and i would like to sort by serial not by name. Please help :S

if you have Python 2.4 or above,

>>> import operator
>>> serial = 12345
>>> total=[[serial,'john'],[serial,'james']]
>>> sorted(total, key=operator.itemgetter(1))
[[12345, 'james'], [12345, 'john']]

or even

key=lambda x:x[1]

Maby an other short method with the help of List Comprehensions: (very fast) [[id,name]for id in range(2)for name in range(3)] Result:
[[0, 0], [0, 1], [0, 2], [0, 3],
[1, 0], [1, 1], [1, 2], [1, 3],
[2, 0], [2, 1], [2, 2], [2, 3]]

ore in this way [[[id]for id in range(2)]for name in range(3)] Result:
[[[0], [1]], [[0], [1]], [[0], [1]]]

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.