Python Advanced Features

Source: Internet
Author: User
Tags iterable

Slice

For the list or tuple, to take part of the elements, with the loop to achieve more trouble, can be easily done with slices .

>>> L = list (range) >>> l[0, 1, 2, 3, ..., 99]

First 10 numbers:

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

0 can be omitted . Number of first 11-20:

>>> l[10:20][10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

is a left and open interval. You can also take negative numbers. 10 Number of second:

>>> l[-10:][90, 91, 92, 93, 94, 95, 96, 97, 98, 99]

All numbers, fetch one per 5:

>>> l[::5][0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]

Don't even write anything, just write [:] to copy a list:

>>> l[:][0, 1, 2, 3, ..., 99]

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

A string ‘xxx‘ can also be seen as a list, with each element being a character. Therefore, a string can also be manipulated with a slice, but the result of the operation is still a string.

Iteration

In Python, you can iterate as long as you have an iterative object, whether or not you have subscript. list, tuple, str, dict ...

>>> d = {' A ': 1, ' B ': 2, ' C ': 3}>>> for key in D: ...     Print (key) ... ACB

Because Dict storage is not ordered in list order, the resulting order of the iterations is likely to be different.

By default, the Dict iteration is key. If you want to iterate over value, for value in d.values() You can use it if you want to iterate both key and for k, v in d.items() value at the same time.

How can I tell if an object is an iterative object? The method is judged by the iterable type of the collections module:

>>> from Collections Import iterable>>> isinstance (' abc ', iterable) # Whether STR can iterate true>>> Isinstance ([i], iterable) # Whether the list can iterate true>>> isinstance (123, iterable) # integer can be iterated false

What if you want to implement subscript loops like Java for a list? Python's enumerate built-in functions can turn a list into an index-element pair so that the for index and the element itself can be iterated at the same time in the loop:

>>> for I, value in enumerate ([' A ', ' B ', ' C ']):     ... Print (i, value) ... 0 A1 B2 C
List-Generated

The list generation, which is the comprehensions, is a very simple and powerful build of Python built-in that can be used to create lists.

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

When writing list generation, it is useful to put the elements you want to generate in front, followed by for loops , to create the list.

The For loop can also be followed by an if judgment so that we can filter out only the even squares:

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

You can also use a two-layer loop to generate a full array:

>>> [M + N for m in ' ABC ' for n ' XYZ ' [' AX ', ' AY ', ' AZ ', ' BX ', ' by ', ' BZ ', ' CX ', ' CY ', ' CZ ']

List generation can also use two variables to generate a list:

>>> d = {' X ': ' A ', ' y ': ' B ', ' z ': ' C '}>>> [k + ' = ' + V for K, V in D.items ()] [' y=b ', ' x=a ', ' z=c ']

Finally, all the strings in a list are converted to lowercase:

>>> L = [' Hello ', ' world ', ' IBM ', ' Apple ']>>> [S.lower () for S in L if Isinstance (s,str)] [' Hello ', ' World ', ' IBM ', ' Apple '
Generator

If you want to generate a very large list, it is a waste of storage space. If the list element can be extrapolated, you do not have to create a complete list, thus saving a lot of space. In Python, this side loop computes the mechanism, called the generator:generator.

There are two ways of creating a generator. One: To change a list-generated []()

>>> L = [x * x for x in range]]>>> l[0, 1, 4, 9, N, F, $, $, 81]>>> g = (x * x for X In range (+) >>> G<generator object <genexpr> at 0x1022ef630>

Print generator with a for loop instead of next (g).

If the calculated algorithm is more complex, and the loop with similar list generation for cannot be implemented, it can also be implemented with functions.

The Fibonacci sequence is not written in a list, but it is easy to print it out with a function:

def fib (max):    N, a, b = 0, 0, 1 while    n < max:        print (b)        A, B = B, a + b        n = n + 1    return ' done '

To turn fib a function into a generator, just print(b) change yield b it to:

def fib (max):    N, a, b = 0, 0, 1 while    n < max:        yield b        A, B = B, a + b        n = n + 1    return ' Done

This is another way to define generator. If a function definition contains a yield keyword, then the function is no longer a normal function, but a generator:

Note: Generator and functions do not have the same execution flow. The function is executed sequentially, the statement is encountered return or the last line of the function is returned . The function that becomes generator, executes at each invocation next() , encounters a yield statement return , and executes again from the last yield statement returned .

Exercise: generating Yang hui triangles

Def triangle (): N=[1]while True:yield nn.append (0) n=[n[i-1]+n[i] for I in range (len (N))]n=0for T in triangle ():p rint (t) n= N+1if N==10:break
Iterators

An object that can directly act on for a loop is called an iterative object: Iterable .

All objects that can be used for next() functions are Iterator types, which represent a sequence of lazy computations;

Collection data types such as list , dict ,, and str so on are Iterable not Iterator , however, you can iter() get an object from a function Iterator .

Turn list , dict and str wait for the Iterable Iterator function to be used iter() :

>>> Isinstance (ITER ([]), Iterator) true>>> isinstance (ITER (' abc '), Iterator) True

The Python for loop is essentially implemented by calling next() functions.

Python advanced features

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.