Python advanced Features-learning notes

Source: Internet
Author: User
Tags generator generator iterable

Python is very useful in advanced features, 1 lines of code can implement the function, never write 5 lines of code. Always keep in mind that the less code you have, the more efficient your development.
1, sliced slice. L = [1, 2, 3, 4, 5]represents, starting from the index, until the index, but not including the index. L[0:3]=[1,2,3] 0 3 3 That is, an index, which 0 1 2 is exactly 3 elements. If the first index is 0 , you can also omit theBottom Slice L[-2:]=[4,5]从倒数第二个数 到 最后一个数
L = List (range (100)) # Creates a 0-99 series ll[:10:2]# the first 10 numbers, each two takes one l[::5]# all numbers, and every 5 takes one iterable. [::-1] # string rollover. Very useful!!
tuple is also a list, only immutable, support slicing operation, the result of operation is still a tupleA ‘xxx‘ string can also be seen as a list, with each element being a character. Therefore, the string can also be used for slicing operations, but the operation result is still a string, equivalent to other programming language string interception function substring, etc.2, Python is for more abstract than the Java cycle for , because the Python for loop can be used not only on the list or tuple, but also on other objects that can be iterated. List this data type although there is subscript, but many other data types are not subscript, but as long as the object can be iterated, whether or not subscript, can iterate, such as dict can iterate, the string can also be iterated.
For key in D: #迭代keyfor value of D.values (): #迭代valuefor K, V in D.items (): #key, value is iterated for-ch in ' ABC ': #字符串, printed separately a,b,c< /SPAN>
3, to judge an object is an iterative object, the method is judged by the iterable type of the collections module:
4. Python's built-in enumerate function 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:

5, in the for loop, also refers to two variables, in Python is very common, such as the following code:


6. List generation: Python built-in very simple but powerful can be used to create a list of the generatedGenerate list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] can be list(range(1, 11))

usedfilter out only the even squares

concatenation of strings with ' + '

list all files and directory names in the current directory >>> import os # 导入os模块,模块的概念后面讲到 >>> [d for d in os.listdir(‘.‘)] # os.listdir可以列出文件和目录,路径可以修改如e:/sublime/python [‘.emacs.d‘, ‘.ssh‘, ‘.Trash‘, ‘Adlm‘, ‘Applications‘]Finally, all the strings in a list are converted to lowercase: >>> L = [‘Hello‘, ‘World‘, ‘IBM‘, ‘Apple‘]
>>> [s.lower() for s in L]
[' Hello ', ' World ', ' IBM ', ' Apple ']The for preceding expression is the action that is required for each item in the iteration, the If Judgment is filtered, written at the end of the list generation, and the result is returned after the operation.
7, Generator generator: To solve the memory problems that need to store all the elements of the list, in the process of the cycle of continuous extrapolation of the subsequent elements, do not have to create a complete list, thus saving a lot of space. ways to create generator:
    • Conversion of list-generated form [](),next()函数获取generator的每一个元素,其实一般很少用该函数,用for循环会更加方便。
      >>> g = (x * x for x in range(10))
      >>> for n in g:
      ...     print(n)
    • 函数定义中使用yieldKeyword: The print that will be interrupted
generating a Fibonacci sequence cannot be done with a list generation, because the list generation can manipulate only the elements of the current iteration and cannot manipulate the two elements in the list. You can print it out with a function and store a list of the first n numbers and consider using the generator: def fib(max):
    n, a, b = 0, 0, 1
While N < max:yield B #  函数打印时为print(b)         a, b = b, a + b
        n = n + 1
return ' Done 'It is also very convenient to get the first max elements with for, because generator can be iterated >>> for n in fib(6):... print (n)
def triangles ():L=[1]yield LWhile True:l=[1]+[l[i]+l[i+1] for I in range (len (L)-1)]+[1]yield L
n = 0For T in triangles ():print (t)n = n + 1if n = = Ten: Break
8. Iterator Object iteratorany object that can be used for for the loop is a Iterable type (iterative);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 . iterators are iterative Iterator Iterable . >>> isinstance(‘abc‘, Iterator)False >>> isinstance(iter(‘abc‘), Iterator)True

Disclaimer: Learn notes from the Liaoche python tutorial--python advanced Features section, thanks to Micheal Liao.

Python advanced Features-learning notes

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.