2

I have written a for loop to display names in python idle as shown below.

1.SRA-D12-TY2-2017WW22.4.129
2.SRA-D12-TY2-2017WW27.5.168
3.SRA-D12-TY2-2017WW16.5.92
4.SRA-D12-TY2-2017WW20.2.115
5.SRA-D12-TY2-2017WW25.2.149
6.SRA-D12-TY2-2017WW29.5.188
7.SRA-D12-TY2-2017WW36.1.234
8.SRA-D12-TY2-2017WW31.3.201

The code I have written to display the above items is

for i in data.get('files'):
    new_data = i.get('uri').strip('/')
    platform_display = "{}.{}".format(count,new_data)
    platform_dict[count] = new_data 
    count += 1
    print platform_display

I want it to be displayed as

1.SRA-D12-TY2-2017WW36.1.234
2.SRA-D12-TY2-2017WW31.3.201
3.SRA-D12-TY2-2017WW29.5.188 

etc in descending order

Please let me know how can I sort the names

3
  • If it will always be the same format, try splitting on 'WW' and then parsing the right side as a float and sorting on that Commented Mar 14, 2018 at 5:56
  • How about using sorted(..., reverse=True)? Commented Mar 14, 2018 at 5:58
  • Can you please give me the code Commented Mar 14, 2018 at 6:06

3 Answers 3

4
l1=[
'SRA-D12-TY2-2017WW22.4.129',
'SRA-D12-TY2-2017WW27.5.168',
'SRA-D12-TY2-2017WW16.5.92',
'SRA-D12-TY2-2017WW20.2.115',
'SRA-D12-TY2-2017WW25.2.149',
'SRA-D12-TY2-2017WW29.5.188',
'SRA-D12-TY2-2017WW36.1.234',
'SRA-D12-TY2-2017WW31.3.201'
]
l1=sorted(l1, key=lambda x: x.split("WW")[-1],reverse=True)
for i in l1:
  print(i)

Output:

SRA-D12-TY2-2017WW36.1.234
SRA-D12-TY2-2017WW31.3.201
SRA-D12-TY2-2017WW29.5.188
SRA-D12-TY2-2017WW27.5.168
SRA-D12-TY2-2017WW25.2.149
SRA-D12-TY2-2017WW22.4.129
SRA-D12-TY2-2017WW20.2.115
SRA-D12-TY2-2017WW16.5.92
Sign up to request clarification or add additional context in comments.

3 Comments

I think x.rsplit("WW") would be more suitable here?
And in this case whole strings can be compared without splitting. Just like this: sorted(l1, reverse=True)
Thanks for the Suggestion @MushifAliNawaz
0

Just use reversed sort.

Lets say all your item in the list called l,

l=['SRA-D12-TY2-2017WW22.4.129',
 'SRA-D12-TY2-2017WW27.5.168',
 'SRA-D12-TY2-2017WW16.5.92',
 'SRA-D12-TY2-2017WW20.2.115',
 'SRA-D12-TY2-2017WW25.2.149',
 'SRA-D12-TY2-2017WW29.5.188',
 'SRA-D12-TY2-2017WW36.1.234',
 'SRA-D12-TY2-2017WW31.3.201']

sorted(l, reverse=True)

1 Comment

Thank you so much it is working i am able to sort the list
0

Try this:

from operator import itemgetter

platform_list = []
for i in data.get('files'):
    new_data = i.get('uri').strip('/')
    platform_list.append([new_data.split("WW")[-1],new_data])

first_item = itemgetter(0)
new_list = sorted(platform_list, key = first_item)
counter = 0
for i in new_list:
    counter += 1
    print "%d.%s" %(counter,i[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.