I am trying to sort by key, but it's not working because I don't think that the thing that I'm trying to sort on counts as a list (in fact I think it is an ndarray?):

y = np.genfromtxt("1400list.txt", dtype=[('filename','S20'),('freq','S20')])

gives me y as something in the form:

[('a070918_215953.SFTC', '1369.000') ('a070918_220602.SFTC', '1369.000')
('a070918_221210.SFTC', '1369.000') ('r080323_044006.SFTC', '1369.000')
etc.]

which is fine - but I want to sort by the first number, and not by the first letter which it is doing at the moment. Can anyone help please?

EDIT: Sorry I should have said that I tried:

y.sort(key=lambda y: y[1])

But I got the error:

TypeError: 'key' is an invalid keyword argument for this function

Thank you in advance.

Edited 4 Years Ago by python1956

Note that the list you posted is not a list of tuples. You can use the older method to do this, although it is slower.

def return_lower(x, y):
    return cmp(x[0][1:], y[0][1:])

test_list=[('a070918_215953.SFTC', '1369.000'), ('a070917_220602.SFTC', '1369.000'),
 ('a070915_221210.SFTC', '1369.000'), ('r080323_044006.SFTC', '1369.000')]

print sorted(test_list, cmp=return_lower)

Thank you! That got rid of my error message, but it didn't seem to sort as I wanted. I need it to sort by the first number of the filenames which begin with a letter, for example:

t090929_161904.SFTC
should come before
a100929_161904.SFTC

Edit: I'm not sure if notation such as "x[0][1:]" will work, because it's a "structured array" or "record array"?

Thank you!

Edited 4 Years Ago by python1956

You are trying to use a Python sort() on a numpy array. To gert this to worek you have to convert the numpy array to a Python list first.

Try something like mynparray.tolist()

This article has been dead for over six months. Start a new discussion instead.