The second core of Python programming is slicing, iteration, and list generation,

Source: Internet
Author: User

The second core of Python programming is slicing, iteration, and list generation,

  Python version: 3.6.2 Operating System: Windows Author: SmallWZQ

It's too busy recently. A lot of things need to be handled by myself. It seems that time is not enough ~~~~ In the future, blog updates may slow down. Hey, that's not the case ...... It seems to be a long journey. OK. Back to the question. Next we will go back to Python first ~~~

In Python programming, If You Want To compile many useful programs, you must master the data types, statements, and functions. For Python programming, there are two principles: first, the code is not the more the better, but the less the better; second, the code is not the more complicated the better, but the simpler the better. You also want to "one line of code for two yuan ". Efficiency determines everything.

The following is an example (otherwise, all text will be dizzy ~~~) [Implement 1, 3, 5, 7, 9 ,...... 99 list ]:

1 # profitable version Code 2 >>> n = 1 3 >>> L = [] 4 >>> while n <= 99: 5... l. append (n) 6... n = n + 2 7... 8 >>> print (L) # a lot of money, but the boss may not necessarily give Oh 9 # slightly reduced version code 10 >>> L = list (range (1,100, 2 )) 11 >>> print (L) 12 # release code 13 >>> [x for x in range (1,100, 2)]

In fact, the Code involved in the above Code mainly includes loops, range (), sharding, and list generation. Through the example, we know that Python provides many useful advanced features. Using these features flexibly can reduce the amount of code and improve efficiency.

Slice

Slicing is one of the advanced features of Python programming. Slice can access elements within a certain range, and use the colon (:) to separate two indexes.

1 # Magic of slicing 2> L = [1, 3, 4, 5, 6, 7, 8, 9, 10] 3> L [2: 5] 4, 4, 4, 55 >>> L [0: 1] 6 1

The implementation of the slice operation requires two indexes as the boundary. The first index element is included in the slice, and the second index is not included in the slice.

Note: If the first index is 0, it can be omitted:

1 >>>L = [1,2,3,4,5,6,7,8,9,10]2 >>>L[0:3]3 1,2,34 >>>L[:3]5 1,2,3

Since Python supports L [-1] to take the first last element, it also supports reciprocal slicing:

1 >>>L = [1,2,3,4,5,6,7,8,9,10]2 >>>L[-2:]3 9,104 >>>L[-2,-1]5 9

In Python 3. x, slicing is also supported.Step Size:

1 >>>L = [1,2,3,4,5,6,7,8,9,10]2 >>>L[::1]3 [1,2,3,4,5,6,7,8,9,10]4 >>>L[0:10:2]5 [1,3,5,7,9]6 >>>L[1:10:5]7 [2,7]

Tuple is also a list. The only difference is that tuple is immutable. Therefore, tuple can also be used for slicing, but the result of the operation is still tuple:

1 >>> (0, 1, 2, 3, 4, 5)[:3]2 (0, 1, 2)

The string 'xxx' can also be considered as a list. Each element is a character. Therefore, the string can also be sliced, but the operation result is still a string:

1 >>> 'ABCDEFG'[:3]2 'ABC'3 >>> 'ABCDEFG'[::2]4 'ACEG'

Python does not have a function to intercept strings. You only need to slice an operation to complete the process, which is very simple.

Python slice is very flexible, and one line of code can achieve many rows of loops to complete the operation.

Iteration

Iteration is the most important advanced feature in Python programming. Iteration: given a list or tupleforLoop to traverse the list or tuple. Therefore, Python uses the for... in loop to implement iteration.

Although the list data type has a subscript, many other data types do not have a lower standard, but as long as it is an iteratable object, it can be iterated regardless of whether there is a subscript, such as dict can be iterated:

1 >>> d = {'A': 1, 'B': 2, 'C': 3}2 >>> for key in d:3 ...    print(key)4 ...5 A6 B7 C8 >>> 

Because the storage of dict is not arranged in the order of list, the order of iteration results may be different.

By default, key is iterated by dict. To iterate the value, you can usefor value in d.values()If you wantIterates key and value at the same time. You can usefor k, v in d.items().

Because the string is also an iteratable object, it can also act onforLoop:

1 >>> for ch in 'ABC':2 ...     print(ch)3 ...4 A5 B6 C

Therefore, when we useforWhen looping, as long as it acts on an iteratable object,forThe loop can run normally, but we do not care about whether the object is a list or other data type.

So how can we determine that an object is an iteratable object? The method is determined by the Iterable type of the collections module:

1 >>> from collections import Iterable2 >>> isinstance ('abc', Iterable) # Can str iterate 3 True4 >>> isinstance ([1, 2, 3], Iterable) # list can be iterated 5 True6 >>> isinstance (123, Iterable) # integer can be iterated 7 False

In the for loop, two variables are referenced at the same time, which is very common in Python, such as the following code:

1 >>> for x, y in [(1, 1), (2, 4), (3, 9)]:2 ...     print(x, y)3 ...4 1 15 2 46 3 9

Any iteratable object can act onforLoop, including our custom data types, can be used as long as the iteration conditions are metforLoop.

List Generator

As an advanced feature of Python programming, the list generator can simplify a lot of code. List Comprehensions is a simple but powerful built-in list generator that can be used to create a List.

For example, to generate a list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], you can use list (range (1, 11 )):

1 >>> list(range(1, 11))2 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

However, if you want to generate [1x1, 2x2, 3x3 ,..., 10x10] How? Method 1: loop:

1 >>> L = []2 >>> for x in range(1, 11):3 ...    L.append(x * x)4 ...5 >>> L6 [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

However, the loop is too cumbersome, and the list generator can use a line of statements instead of generating the above list cyclically:

1 >>> [x * x for x in range(1, 11)]2 [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

When writing the list generator, put the x element to be generated in front, followed by the for loop, you can create the list, and add if judgment after the for loop, in this way, we can filter out the even square:

1 >>> [x * x for x in range(1, 11) if x % 2 == 0]2 [4, 16, 36, 64, 100]

The list generator can also use two variables to generate the list:

1 >>> d = {'x': 'A', 'y': 'B', 'z': 'C' }2 >>> [k + '=' + v for k, v in d.items()]3 ['y=B', 'x=A', 'z=C']

Converts all strings in a list to lowercase:

1 >>> L = ['Hello', 'World', 'IBM', 'Apple']2 >>> [s.lower() for s in L]3 ['hello', 'world', 'ibm', 'apple']

The list generator is not a real statement, but a loop expression. This is why it is classified as a loop statement. This function is very powerful, but in most cases, it can also be completed directly using loops and conditional statements. However, the list-based program is concise and easier to read.

The following is an example:

1 L1 = ['Hello', 'World', 18, 'Apple', None]2 L2= [s.lower() for s in L1 if isinstance(s,str)]

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.