1

My list condition are in String. so, I want to sorted the second condition from big to small, but "-" does not working for me. my code is:

import operator
a = int(input())
my_list = []
for i in range(a):
    data = list(map(str, input().split()))
    my_list.append(data)

result = sorted(my_list, key= operator.itemgetter(2, 1, 0))

for i in range(len(result)):
    print(result[i][0])

for input for example:

6
Elon 22 2017
Jakob 22 2017
ali 20 2018
sina 30 2008
donald 33 2005
jo 31 2018

the first item is name. second is age. and the last is year. so, the Priority for me is year, age from big to small and the name. I know, that i can use sorted() and choose the priority, but the second condition must be in reverse. I was searching, and found that if I use "-" before the condition and then call "reverse=True" the condition that have "-", will be reversed. but my condition is string and it does not working!

now, the output is:

donald
sina
Elon
Jakob
ali
jo

but I expected:

donald
sina
Elon
Jakob
jo
ali
6
  • Could you please post your expected output? Commented May 28, 2020 at 5:57
  • 1
    @Bogota Sure. I add the output on the end of my post. Commented May 28, 2020 at 6:02
  • Please include the code where you use "-" and that does not work instead of just describing it, along with the complete error message. Commented May 28, 2020 at 6:07
  • @timgeb Thank you for you answer. The code in below was answering my question and it is work now. Commented May 28, 2020 at 6:16
  • 1
    @timgeb Yes, Sure :) Commented May 28, 2020 at 6:43

1 Answer 1

2

Try this:

result = sorted(mylist, key=lambda x: (x[2], -int(x[1])))
for x in result:
    print(x[0])

Output

donald
sina
Elon
Jakob
jo
ali
Sign up to request clarification or add additional context in comments.

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.