1

i have an array and fill it like this

arr = [[],[]]
arr[0].append(post.attrib['href']) #strings
arr[1].append(int(klass)) # int

and i need to sort whole array by arr[1] for example input:

[['string3', 'string45', 'string25'], [46, 2, 12]]

and output:

[['string45', 'string25', 'string3'], [2, 12, 46]]

i tried

arr[0].sort(key = x[1].__getitem__) 
arr[0].sort(key=lambda x: x[1])
arr = sorted(arr, key=itemgetter(1))

but everything of this isn't working correct

1
  • What's the output of your code? Commented Dec 20, 2013 at 17:26

3 Answers 3

7

As you are sorting composite elements, create a pair of those elements you intend to sort using (zip or itertools.izip), and use operator.itemgetter, to select the correct key. Finally transpose back to the original format using zip.

from operator import itemgetter
zip(*sorted(zip(*arr), key = itemgetter(1)))
[('string45', 'string25', 'string3'), (2, 12, 46)]

This idea can be extended to multiple keys in a list.

Steps of Execution

>>> arr #Original Array
[['string3', 'string45', 'string25'], [46, 2, 12]]
>>> zip(*arr) #Unpacking the array, transposes it
[('string3', 46), ('string45', 2), ('string25', 12)]
>>> sorted(zip(*arr), key = itemgetter(1)) #Sort the Transpose Array based on second element
[('string45', 2), ('string25', 12), ('string3', 46)]
>>> zip(*sorted(zip(*arr), key = itemgetter(1))) #Transpose the result to generate the original format
[('string45', 'string25', 'string3'), (2, 12, 46)]
Sign up to request clarification or add additional context in comments.

4 Comments

what exactly does the ' * ' in front of sorted do? I've never seen it used in front of a built in function before
I know that, but i just don't get how it works when applied to 'sorted'
@Totem: It applies to zip rather than to sorted. The Output of sorted is unpacked and passed to zip. Let me add the steps of execution to the answer
1

Have you considered storing your data as one list of 2-element pairs (e.g. [(46, 'string3'), (2, 'string45'), (12, 'string25')]) instead? Because if you did that, your problem would solve itself in one line of code:

l = [(46, 'string3'), (2, 'string45'), (12, 'string25')]
print sorted(l) 
# [(2, 'string45'), (12, 'string25'), (46, 'string3')]

By the way, they're lists, not arrays. Arrays in Python mean something else (namely, NumPy arrays).

1 Comment

yeah i know) but habitually after js i call it arrays)
0

I find packing and unpacking arguments a little bit unintuitive at times, so

l = [['string3', 'string45', 'string25'], [46, 2, 12]]
[[y[1] for y in sorted(zip(l[1], x))] for x in l]
[['string45', 'string25', 'string3'], [2, 12, 46]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.