0

So.. Actually, I have a list that has multiple strings on it. And here I want to sort it in specific strings index :

lists = ['AELIA4560005253120', 'KIFLA5000005760000']

Soo.. inside of the lists, there are names (which has caps word in it), code (3 number digits after the name), and secret number (10 digits of code after the previous code).. my question is, can I sort this list by specific strings index which I want to sort it by code (3 number digits after the name)??

# expecting lists after sort
lists_sort = ['KIFLA5000005760000','AELIA4560005253120']

So my expected result is, KIFLA came first and AELIA is second is because KIFLA's codes are 500 and AELIA's codes are 456

Can anyone help me? thank you 😁

4
  • Are the names always the same length? Commented Jun 13, 2020 at 5:28
  • Nope.. only the secret codes have the same length which is 10 digit of last codes. Commented Jun 13, 2020 at 5:45
  • So then the answer you accepted will break if the names are not exactly five letters long. Commented Jun 13, 2020 at 5:47
  • Yea, But thanks to the answer, I can improvise the code by changing the index by reverse the index itself which the codes become like this.. res = sorted(lists, key=lambda x: int(x[-13:-10]), reverse = True) Commented Jun 13, 2020 at 5:53

2 Answers 2

2

Try this:

lists = ['AELIA4560005253120', 'KIFLA5000005760000']

res = sorted(lists, key=lambda x: int(x[5:8]) , reverse = True)
#['KIFLA5000005760000', 'AELIA4560005253120']
Sign up to request clarification or add additional context in comments.

1 Comment

You probably want int(x[5:8]) in the lambda function.
1

Assuming the name is of a variable length, you can use this:

import re

lists = ['AELIA4560005253120', 'KIFLA5000005760000']

lists_sort = sorted(lists, key = lambda x: int(re.search(r'\d{3}', x).group(0)), reverse = True)
print(lists_sort)

2 Comments

I wonder if int(re.search(r'\d{3}', s).group(0)) would be easier?
yeah, thanks for the suggestion. I've updated the answer

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.