0

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

5
Contributors
4
Replies
5
Views
9 Years
Discussion Span
Last Post by PlagTag
0

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']]

Edited by vegaseat: changed code tags

0

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']]
0

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]]]

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.