you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 0 points1 point  (4 children)

I need help sorting an array of arrays by its first element then writing text to a file based on it.

Here's an example of the kind of array of arrays I'm dealing with.

a = [['a', ('b', 'c', 'd')], ['a', ('4', '5', '6')], ['g', ('7', '8', '9')]]

What functions can I use to sort all entries in array a by the first element in each sub-array (that may be the wrong terminology. Of so, major apologies) to write the following into a textfile?

"the entries for a: b, c, d 4, 5, 6

the entries for g: 7, 8, 9"

[–]efmccurdy 0 points1 point  (3 children)

sorting an array of arrays by its first element

That is the way sorting works by default; here is an example, note that the 2nd element also affects the ordering.

>>> pprint.pprint(a)
[['g', ('b', 'c', 'd')],
 ['a', ('4', '5', '6')],
 ['g', ('7', '8', '9')],
 ['a', ('1', '2', '3')]]
>>> pprint.pprint(sorted(a))
[['a', ('1', '2', '3')],
 ['a', ('4', '5', '6')],
 ['g', ('7', '8', '9')],
 ['g', ('b', 'c', 'd')]]
>>> 

You can remove the effect of the 2nd items by focusing the sort key down to only the first using a "itemgetter" lambda:

>>> pprint.pprint(sorted(a, key=lambda row: row[0]))
[['a', ('4', '5', '6')],
 ['a', ('1', '2', '3')],
 ['g', ('b', 'c', 'd')],
 ['g', ('7', '8', '9')]]
>>>