The path to Python Learning (9)-sorted () sorting and simple string processing

Source: Internet
Author: User
Tags uppercase letter

The path to Python Learning (9)-sorted () sorting and simple string processing

This section describes two knowledge points: 1 sorting and 2 string processing.

Python has well encapsulated this part of the sorting operation. We can achieve the sorting effect without writing too much code. First paste the Java implementation. (This is not a black Java !!!!)

Public class directly inserts the sort {public static void main (String [] args) {int [] a = {,}; System. out. println ("Before sorting:"); for (int I = 0; I <. length; I ++) {System. out. print (a [I] + "");} // Insert the sort directly for (int I = 1; I <. length; I ++) {// The element to be inserted int temp = a [I]; int j;/* for (j = I-1; j> = 0 & a [j]> temp; j --) {// move a digit greater than temp to a [j + 1] = a [j];} */for (j = I-1; j> = 0; j --) {// move a future greater than temp if (a [j]> temp) {a [j + 1] = a [j];} else {break;} a [j + 1] = temp;} System. out. println (); System. out. println ("sorted:"); for (int I = 0; I <. length; I ++) {System. out. print (a [I] + "");}}}
Public class binary insertion sorting {public static void main (String [] args) {int [] a = {176,213,227,}; System. out. println ("Before sorting:"); for (int I = 0; I <. length; I ++) {System. out. print (a [I] + "");} // binary insert sort (a); System. out. println (); System. out. println ("sorted:"); for (int I = 0; I <. length; I ++) {System. out. print (a [I] + "") ;}} private static void sort (int [] a) {for (int I = 0; I <. length; I ++) {int temp = a [I]; int left = 0; int right = I-1; int mid = 0; while (left <= right) {mid = (left + right)/2; if (temp = left; j --) {a [j + 1] = a [j];} if (left! = I) {a [left] = temp ;}}}}

Similarly, Python of the bubble type is relatively easy to encapsulate in this part.

List = [1, 3,-1, 8, 9] print ('sorting pre', list, 'Basic sorting Post', sorted (list) results: [1, 3,-1, 8, 9] After basic sorting [-1, 1, 3, 8, 9]

Of course, like the previous high-level methods such as map, there are optional options, or you can use the simplest sorting in the example. (So all the objects to be sorted are iterable objects)

Let's take a look at the implementation of sorted.

def sorted(*args, **kwargs): # real signature unknown    """    Return a new list containing all items from the iterable in ascending order.    A custom key function can be supplied to customise the sort order, and the    reverse flag can be set to request the result in descending order.    """    pass

In the vernacular

sorted(iterable[,cmp,[,key[,reverse=True]]])

There are three optional parameters: cmp, key, and reverse.
1) cmp specifies a custom comparison function. This function receives two parameters (iterable elements). If the first parameter is smaller than the second parameter, a negative value is returned; if the first parameter is equal to the second parameter, zero is returned. If the first parameter is greater than the second parameter, a positive number is returned. The default value is None.
2) key specifies a function that receives a parameter. This function is used to extract a keyword for comparison from each element. The default value is None.
3) reverse is a Boolean value. If this parameter is set to True, the list elements are sorted in reverse order.

YesSorted ()Methods are also available.List. sort ()Method, but the list. sort () method will replace the data of the original iterator, So it depends on your specific needs.

Starting from Python2.4, the list. sort () and sorted () methods both add a key parameter to declare a function. This function will call each element in the list before comparison.

In this way, sort the original basic order according to certain business needs.

Print ('sort by absolute value ', sorted (list, key = abs) Results: sort by absolute value [1,-1, 3, 8, 9]

Can the string be split?

DaXie = "Wo de ming Zi Jiao Wjj" print ('split string', sorted (daXie. split (), key = str. (lower) Result: The split string ['des', 'jiao', 'ming', 'wjj ', 'Wo', 'zi']

Strings can also be split!

So how to operate complex objects? Similar to an attribute of an element in a tuples.

People = [('wj1', 'A', 99), ('wjj2 ',' B ', 100), ('wjj3', 'C', 45 ), ('wj4', 'D', 75),] print ('object sorting result: ', sorted (people, key = lambda person: person [2]) print ('object sorting level: ', sorted (people, key = lambda person: person [1]) Result: Object sorting result: [('wj3 ', 'C', 45), ('wjj4', 'D', 75), ('wj1', 'A', 99), ('wjjj2 ',' B ', 100)] object sorting level: [('wj1', 'A', 99), ('wjjj1', 'B', 100), ('wjj3 ', 'C', 45), ('wj4', 'D', 75)]

Is it easy to use the benchmark that sorts scores by level (English characters?

Introduce some simple string processing

First, some case-sensitive operations are displayed:

DaXie = "wo shi Wjj" print ('write bigger and smaller: ', daXie. result of lower (): write with a higher write size: wo shi wjxiaoxie = 'Wo shi Wjj 'print ('lower case to upper case: ', xiaoXie. upper () Result: lowercase to uppercase: wo shi WJJprint ('case-insensitive: ', xiaoXie. swapcase (), '', daXie. swapcase () Result: case-insensitive: wo shi wJJ wo shi wJJprint ('capitalized ', xiaoXie. title () Result: uppercase letter: Wo Shi Wjj

And then the formatting operation.

Print ('left alignment: ', daXie. ljust (15, "a") Result: Left alignment: wo shi Wjjaaaaaprint ('Right indent: ', daXie. result: Right indent: bbbbbWO SHI wjprint ('center processing: ', xiaoXie. center (15, 'C') Result: center processing: cccwo shi Wjjccprint ('fill processing: ', daXie. zfill (15) Result: Fill processing: 00000WO SHI Wjj

If you want to fill the string, you can fill it with spaces without filling it. (If you cannot fill it with more than one character, an error is reported. Therefore, zfill () is used as a space. The default value is 0)

There are operations to add indentation, and of course there are also effects to remove indentation

Print ('remove spaces on both sides: ', 'abc cc dd '. strip () Result: remove the space on both sides: abc cc ddprint ('Remove the left space: ', 'abc cc dd '. lstrip () Result: remove the left space: abc cc dd print ('Remove the right space: ', 'abc cc dd '. rstrip () Result: remove the space on the right: abc cc dd

Advanced languages are much easier to use than the old ones, but in the end they are the same. After all, the language is just a tool. However, there are more than one craft to get out of it. Hahaha has a pleasant spring festival !!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.