Issue
I want to sort a list of numeric strings (w/ trailing zeroes) like how you normally sort number. I'd also like to return a True bool if a provided numeric string is in that list.
Example:
old_list = [1.1, 1.8, 1.50, 1.5, 1.9, 2.1]
to
sorted = [1.1, 1.5, 1.8, 1.9, 1.50, 2.1]
So, obviously the decimals are treated like numbers and sorted like numbers. 1.50 should not be simplified as 1.5, etc. It is used for product id for my company and has been bothering me for a year already.
I have tried converting the numeric strings into str then sort. I also tried using the Decimal module but it turns 1.1 into sth like 1.10000000000000008881...
Here is the code I used:
object_num = list(map(str, ['1.1', '1.8', '1.50', '1.5', '1.9', '2.1']))
object_num.sort()
print(object_num)
Result:
['1.1', '1.5', '1.50', '1.8', '1.9', '2.1']
I appreciate that Python is smart enough to sort the list numerically, but I hope it could also get me this result:
sorted = [1.1, 1.5, 1.8, 1.9, 1.50, 2.1]
And when I typed
print(1.50 in sorted)
It could return True.
Edit1: sorry for not making myself clear. Let me explain the numbering system my company is using:
ID for first product from series A: 1.1
ID for second product from series A: 1.2
...
ID for fiftieth product from series A: 1.50
ID for first product from series B: 2.1
All I want is to sort products from series A first, then series B
Thus, 1.5 is indeed different from 1.50 in my case
Solution
One solution using re
module:
import re
lst = ['1.1', '1.8', '1.50', '1.5', '1.9', '2.1']
l = sorted(lst, key=lambda k: [*map(int, re.findall(r'\d+', k))])
print(l)
Prints:
['1.1', '1.5', '1.8', '1.9', '1.50', '2.1']
Or without re
:
l = sorted(lst, key=lambda k: [*map(int, k.split('.'))])
print(l)
Answered By - Andrej Kesely Answer Checked By - Clifford M. (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.