This article example describes the python implementation of ignoring case on the string list sorting method, is very practical skills. Shared for your reference. Specific analysis is as follows:
Let's start with the following code:
string = ''' the stirng Has many line In THE fIle jb51 net ''' list_of_string = () print list_of_string # Separate strings into lists print '*'*50 def case_insensitive_sort(liststring): listtemp = [((),x) for x in liststring]# Take a list of strings, generate a tuple, (ignore case-sensitive strings, strings) ()# Sort the tuple as the tuple is: (case-neglected string, string), that is, sort by case-neglected string return [x[1] for x in listtemp]# Return a list of the original strings when sorting is complete print case_insensitive_sort(list_of_string)#Call it up and test it
Results:
['the', 'stirng', 'Has', 'many', 'line', 'In', 'THE', 'fIle', 'jb51', 'net'] ************************************************** ['fIle', 'Has', 'In', 'jb51', 'line', 'many', 'net', 'stirng', 'THE', 'the']
Another approach:
Using Built-in Functions
sorted(iterable[,cmp[, key[,reverse]]])
The official description of this function is documented below:
Return a new sorted list from the items in iterable.
key specifies a function of one argument that is used to extract a comparison key from each list element:key=. The default value isNone.
Use the parameter key=
The full code is below:
string = ''' the stirng Has many line In THE fIle jb51 net ''' list_of_string = () print list_of_string # Separate strings into lists print '*'*50 def case_insensitive_sort2(liststring): return sorted(liststring,key = ) print case_insensitive_sort2(list_of_string)#Call it up and test it
The effect is the same.
Method Three:
Use the sort method of list:
The official documentation describing this method is as follows:
The sort() method takes optional arguments for controlling the comparisons.
cmp specifies a custom comparison function of two arguments (list items) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument: cmp=lambda x,y: cmp((), ()). The default value is None.
key specifies a function of one argument that is used to extract a comparison key from each list element: key=. The default value is None.
reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.
The specific code is as follows:
string = ''' the stirng Has many line In THE fIle jb51 net ''' list_of_string = () print list_of_string # Separate strings into lists print '*'*50 def case_insensitive_sort3(liststring): (cmp=lambda x,y: cmp((), ())) case_insensitive_sort3(list_of_string) print list_of_string
But there's a difference in this call.
Interested friends can debug and run the examples in this article to deepen the impression, I believe there will be new gains!