[PYTHON] Sorting with mixed numbers and letters

import numpy as np
import re

def isd(N):
    return bool(re.compile("^[-+]?([0-9]+(\.[0-9]*)?|\.[0-9]+)([eE][-+]?[0-9]+)?$").match(N))

def sort(A):
	B=list(np.copy(A))
	B.sort(key = lambda x: float(x) if isd(x) else x)
	return B

def argsort(A):
	B=list(np.copy(A))
	B=sort(B)
	return [B.index(i) for i in A]

###
A=['0', '1', '10', 'c0', '12', '13', '34','-3.', '1e+2','16', 'c1','test', 'b0', '3','0.1','1.2','1e-3']
print A
print sort(A)
print argsort(A)

Output result

['0', '1', '10', 'c0', '12', '13', '34', '-3.', '1e+2', '16', 'c1', 'test', 'b0', '3', '0.1', '1.2', '1e-3']
['-3.', '0', '1e-3', '0.1', '1', '1.2', '3', '10', '12', '13', '16', '34', '1e+2', 'b0', 'c0', 'c1', 'test']
[1, 4, 7, 14, 8, 9, 11, 0, 12, 10, 15, 16, 13, 6, 3, 5, 2]

Recommended Posts

Sorting with mixed numbers and letters
Distinguish between numbers and letters with regular expressions
Script to tweet with multiples of 3 and numbers with 3 !!
Ten Puzzle-Make 10 with only 4 numbers and 4 arithmetic operations
Prime numbers and divisors
Algorithm learned with Python 18th: Sorting (stack and queue)
Generate Fibonacci numbers with Python closures, iterators, and generators
Converts numbers with commas and triangles to numeric types.
With and without WSGI
Display numbers and letters assigned to variables in python print
Programming with Python and Tkinter
Encryption and decryption with Python
Mixed Gaussian distribution and logsumexp
Working with tkinter and mouse
Python and hardware-Using RS232C with Python-
Determine prime numbers with python
Sorting image files with Python (2)
Sorting image files with Python (3)
Sorting image files with Python
Extract numbers with regular expressions
Super-resolution with SRGAN and ESRGAN
group_by with sqlalchemy and sum
python with pyenv and venv
With me, NER and Flair
Works with Python and R