2

I have a list which contains the following

a= [june,32,may,67,april,1,dec,99]

I want to sort only the numbers in descending order but it should display with corresponding pair:

Output Expected
----------------
dec,99,may,67,june,32,april,1

I tried to sort using a.sort(reverse=True) command in the list not getting the expected output,this one is confusing a lot.

4
  • 01 is invalid in Python3 (it's old 2.7 octal notation). strings need to be quoted Commented Jun 5, 2018 at 13:48
  • @tonypdmtr edited Thanks.!! Commented Jun 5, 2018 at 13:54
  • (you missed the 2nd part) ... strings need to be quoted: a = ['june',32,'may',67,'april',1,'dec',99] Commented Jun 5, 2018 at 13:59
  • a = [x for s in [[b,a] for a,b in sorted([(a[i],a[i-1]) for i in range(len(a)) if i%2 == 1],reverse=True)] for x in s] Commented Jun 5, 2018 at 14:31

2 Answers 2

5

You can use a list of tuples:

a = ['june', '32', 'may', '67', 'april', '01', 'dec', '99']

zipper = zip(a[::2], a[1::2])

res = sorted(zipper, key=lambda x: -int(x[1]))  # or, int(x[1]) with reverse=True

print(res)

[('dec', '99'), ('may', '67'), ('june', '32'), ('april', '01')]

If you need to flatten, use itertools.chain:

from itertools import chain

res = list(chain.from_iterable(res))

['dec', '99', 'may', '67', 'june', '32', 'april', '01']
Sign up to request clarification or add additional context in comments.

Comments

2

You can first create nested lists containing the month-value pair, apply sorted, and then flatten:

a= ['june',32,'may',67,'april',01,'dec',99]
new_a = sorted([[a[i], a[i+1]] for i in range(0, len(a), 2)], key=lambda x:x[-1], reverse=True)
final_a = [i for b in new_a for i in b]

Output:

['dec', 99, 'may', 67, 'june', 32, 'april', 1]

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.