Python Learning Notes-Advanced features __python

Source: Internet
Author: User
Tags function definition generator iterable lowercase

This article is a learning note for the Liaoche Python tutorial
Specific content, you can refer to the following links:
http://www.liaoxuefeng.com/ 1. Slice (Slice)

Intercept a section from a list, tuple, or string.
[i:j: K] means to remove part of the element in the open interval of <= index < J in the list with a step length of k, and the step defaults to 1, if K < 0, which indicates an inverted slice.

L = List (range)
#取出L [0], l[1], l[2]
L[0:3]
2. Iteration

does not use subscript to traverse any iteration object. such as list, tuple, Dict, string.

#迭代dict类型
#默认对key迭代 for
key in D:
    print (key)
#迭代value for value in
d.values ():
    print (value)
#同时迭代key, value for
key, value in D.items ():
    print (key, value)

Determine whether an object can be iterated , and judge by the type of iterable of the collections module.

From collections import iterable
#判断对象是否可迭代, return True or False
isinstance (obj, iterable)

If you use the subscript loop , the function enumerate () can turn the list into an index-element pair that iterates through the indexes and elements in the For loop.

L = ' ABCDEFG '
for I, value in enumerate (L):
    print (I, value)
3. List-generation (comprehensions)

The build that is used to create the list.
element is generated in the previous, with a for statement. You can add if to judge, and you can double loop.

#for语句, generate results [1, 4, 9,, BA, M, M]
[x * x for x in range (1, one)]
#if语句, preserving even squares only, generating results [4, 16, 36, 64,
[x * x for x in range (1, one) if x 2 = 0]
#双层循环, generate all permutations, generate results [' AX ', ' AY ', ' AZ ', ' BX ', ' by ', ' BZ ', ' CX ', ' CY ', ' CZ ']
[m + N for m in ' abc ' for n in ' XYZ ']
#三层循环, all aligned, results [' aX1 ', ' aX2 ', ' aY1 ', ' aY2 ', ' bX1 ', ' bX2 ', ' bY1 ', ' bY2 ']< C9/>[m + n + q for m in ' AB ' for n in ' XY ', q in ' 12 '

Lists all file and directory names under the current directory.
Os.listdir () can list files and directories.

#导入os模块
import os
dirs = [dir for dir in Os.listdir ('. ')]
Print (dirs)

Changes all strings in the list to lowercase.

L = [' A ', ' B ', ' C ', ' D ']
print ([E.lower () to E in L])
print (L)

The output results are:

[' A ', ' B ', ' C ', ' d ']
[' A ', ' B ', ' C ', ' D ']

The list generation is reborn into a list and does not change the value of the original list.
If the list contains both a string and an integer, because the lower () method does not have a string type, it will give an error, and you can use the Isinstance () function in the IF statement to determine whether the element is a character type and then lowercase.

L = [' Hello ', ' World ', #, ' Apple ', None]
[S.lower () for S in L if Isinstance (S, str)]
#结果为 [' Hello ', ' world ', ' app Le ']
4. Generator (generator)

The builder does not have to create a complete list, so it can save a lot of space by calculating the list element to use while looping.
To change the list-generated [] to (), you can create a generator.
You can print out each element of the list directly, and generator gets the next return value through next () .
Generator saves the algorithm by calling next (g) to compute the value of the next element of G until the last element is computed, and no more elements are thrown when the stopiteration error is raised.
Generator is an iterative object that can be printed using a for loop, with a for loop iteration, and without fear of stopiteration errors when no elements are available to print.

L = [2 * x for x in range (1, 6)]
g = (2 * x for x in range (1, 6))
print (l)
#直接打印generator会报错
Print (g)
Print (Next (g))
# Print (Next (g))
print (' for ')
#for循环接着当前已经打印过的元素打印 to
N in G:
    print (n)

The results are as follows:

[2, 4, 6, 8,]
<generator object <genexpr> at 0x01d81c10>
2
for
4
6
8
10

If a function definition contains the yield keyword, then the function is no longer a normal function, but rather a generator,yield statement instead of a print statement.
For example, print the number of the first n of the Fibonacci sequence

#打印斐波那契数列的前n个数
def fib (max):
    N, a, B, = 0, 0, 1 while
    n < max:
        yield (b)
        A, B = b, a+b
        n = n + 1 return
    "Done"

f = fib (5)
#可以使用for语句打印f中的所有元素
# for Num in F:
#   print (num)
Print (Next (f)) print (Next (f)) print

Each time the next () function is called, the equivalent function fib () executes to the yield statement, prints the result, and when the next next is called, continues execution from the last yield, encounters a return statement, or executes to the last line of statement, ending the generator. The results are:

1
1
2

However, when you call generator with a For loop, you cannot get the return value of the generator returns statement. If you want to get the return value, you must catch the Stopiteration error, and the return value is contained in stopiteration value.
Again for example, print the first n lines of the Yang Hui's triangle:

def triangles ():
    Prel = [] While
    True:
        newl = []
        a = 0 for
        b in Prel:
            newl.append (a+b)
            a = b
  newl.append (1)
        Prel = newl
        yield (newl)
#打印杨辉三角的前10行
n = 0 for
t in triangles ():
    print ( T)
    n = n + 1
    if n =: Break
        

The results are as follows:

[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, ten, 5, 1]
[1, 6, 6, 1]
[1, 7, A, KM, 7, 1]
[1, 8, A, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
5. Iterators

An object that can be directly applied to a for loop is called an iterative object: Iterable.
Data types that can be iterated include collection data types (such as list, tuple, dict, set, str, and so on) and generators.
All objects that can be used for a for loop are iterable types;
Objects that can be used for the next () function are iterator types that represent a sequence of lazy computations that are computed only if the next data needs to be returned.
Iterator can represent an infinitely large stream of data, but the list is not available.
Collection data types such as list, dict, str, etc. are iterable but not iterator, but you can get a iterator object from the iter () function.

From collections import iterable
to collections import iterator
L = [1, 2, 3]
G = (x for x in range (1, 4)) 
   #list是可迭代对象但不是迭代器
Print (Isinstance (l, iterable))  #True
print (Isinstance (l, iterator))  #False    
#生成器既是可迭代对象又是迭代器
Print (Isinstance (g, iterable))  #True
Print (Isinstance (g, iterator))  # True
#iter () function converts an iterative object to an iterator
L1 = iter (l)
print (Isinstance (l, iterator))  #False
Print ( Isinstance (L1, iterator)) #True
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.