2

I was wondering if there is any data structure in python that can fulfil my requirements.

I have a tuple of such

(item1, item2, item3, count)

I would like to sort by count in descending order. Is there any structure i could use in python to achieve this? The elements can be reordered if necessary.

Yes i have a list of tuples which will look like this above

4
  • Do you mean you have a list of tuples, where the tuples look like above? Commented Sep 10, 2015 at 7:10
  • Do you mean - sorting by indexes like 1(item1), 2 (item2)...? Commented Sep 10, 2015 at 7:10
  • sorted(tuple,reverse=True) will this solve your problem Commented Sep 10, 2015 at 7:13
  • Answered all the questions. Commented Sep 10, 2015 at 7:14

5 Answers 5

3

If you have a list of tuples, where each tuple looks like -

(item1, item2, item3, count)

Then you can use sorted() function with key argument and operator.itemgetter(3) to get the 4th element from the tuple to sort based on , and reverse=True to sort in descending order. Example -

import operator
sorted(lst, key=operator.itemgetter(3),reverse=True)

You can also use operator.itemgetter(-1) , if you want to get the last element from the tuple.

Sign up to request clarification or add additional context in comments.

Comments

1

sorted(tuple,reverse=True) should solve your problem

Comments

1

Given list of tuples:

l = [(a1, b1, c1, count1), (a2, b2, c2, count2), ...]

You may simply do:

l.sort(key=lambda t: t[-1], reverse=True)

Comments

1

Or use your old friend lambda:

l.sort(lambda x,y:cmp(y[3],x[3]))

Where "l" is the name of your list.

Comments

1
>>> values = [
...     ('asdf', 'qwer', 'zxcv', 5),
...     ('qwer', 'asdf', 'zxcv', 9),
...     ('zxcv', 'qwer', 'asdf', 2)
... ]

>>> sorted(values, key=lambda value: value[3], reverse=True)
[('qwer', 'asdf', 'zxcv', 9),
 ('asdf', 'qwer', 'zxcv', 5),
 ('zxcv', 'qwer', 'asdf', 2)]

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.