Python's advanced features slice, iterate, list generation, generator

Source: Internet
Author: User
Tags iterable

Slice

A slice is a partial element that gets a list, a tuple, a string, and so on
1L = Range (100) 2 #take [0,5] element3 Print(L[:5])#[0, 1, 2, 3, 4]4 #in [0,99], take one of every 10 elements5 Print(L[::10])#[0, ten , +, +, +,--6 #take the last five elements7 Print(l[-5:])#[98, ©8 9str ="www.genekang.com" Ten #can also be used to intercept strings One Print(Str[4:8])#Gene

Iteration If given a list or tuple, we can pass for loop to traverse the list or tuple, which iterates over us as an iteration (iteration)  
1MyList = ['a','b', 123,'ABC']2 3 #iterate over a list4 5  forKinchmyList:6 7     Printk8 9 #Python's built-in enumerate function can turn a list into an index-element pairTen  One #0 A A  - #1 B -  the #2 123 -  - #3 ABC -  +  forI,kinchEnumerate (myList): -  +     PrintI,k

In addition to list, the dict iteration is key. If you want to iterate over value, you can use thefor value in d.itervalues(), you can use it if you want to iterate both key and value at the same time for k, v in d.iteritems() .

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) # str是否可迭代True>>> isinstance([1,2,3], Iterable) # list是否可迭代True>>> isinstance(123, Iterable) # 整数是否可迭代False
List-generatedThe list-generated type, which is comprehensions, is a very simple and powerful built-in Python build that can be used to create lists.
1 #calculates the square of an even number in 1-102 3ll =range (1,11)4 5 Print[X*x forXinchllifX% 2 = =0]6 7  8 9 #you can also double-cycleTen  One Print[i + J forIinch "AB"  forJinch "CD"]#[' AC ', ' ad ', ' BC ', ' BD '] A  -   -  the #list generation can also use two variables to generate the list -  -D = {'x':'A','y':'B','Z':'C' } -  + Print[k +':'+ V forKvinchD.iteritems ()]#[' y:b ', ' x:a ', ' z:c ']

Generator in Python, this side loop computes the mechanism, called the Generator (Generator), equivalent to an iterator in Java (iterator)
There are a number of ways to create a generator. The first method is simple, as long as a list-generated []Changed () to create a generator
 
1 using a function to implement a Fibonacci sequence2 3 #1 1 2 3 5 84 5 deffib (max):6 7N,a,b = 0,0,18 9      while(n<max):Ten  One         Printb A  -A, B = B, A +b -  then = n+1

Looking closely, it can be seen that the fib function is actually a calculation rule that defines the Fibonacci sequence, which can be derived from the first element, and the subsequent arbitrary elements, which are actually very similar to generator.

In other words, the above functions and generator are only a step away. To turn fib a function into a generator, just print b change yield b it to:

1 deffib (max):2 3N,a,b = 0,0,14 5      while(n<max):6 7         yieldb8 9A, B = B, A +bTen  Onen = n+1 A  -  forXinchFIB (6): -  the     PrintX

Python's advanced features slice, iterate, list generation, generator

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.