A brief analysis of Python iterator examples _python

Source: Internet
Author: User
Tags generator iterable

This article illustrates the simple use of Python iterators and share them for your reference. The specific analysis is as follows:

A builder expression is an iterator that is used to generate sequence parameters when a function is called

The generator object can be traversed or transformed into a list (or data structure such as a tuple), but it cannot be sliced (slicing). When the unique argument of a function is an iterative sequence, you can remove the parentheses at both ends of the generator expression and write more elegant code:------------->

>>>> sum (i for I in Xrange ())
 45

Sum declaration:

Sum (iterable[, start))
Sums start and the items of a iterable from left to right and returns the total. Start defaults to 0. The iterable ' s items are normally numbers, and are not allowed to be strings. The fast, correct way to concatenate a sequence of strings are by calling '. Join (Sequence). Note This sum (range (n), m) is equivalent to reduce (Operator.add, range (n), m) to add floating point values with extended p Recision, Math.fsum ().

Parameters require passing in an iterative sequence, and we pass in a generator object that is perfectly implemented.

Note that the following code is distinguished:

The J above is the generator type, and the following J is the list type:

j = (I for I in range (a)) print 
J,type (j) 
print ' * ' *70 
 
j = [I for I in Range (Ten)] 
print J,type (j) 

Results:

<generator object <genexpr> at 0x01cb1a30> <type ' generator ' >
********************************
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] <type ' list ' >

I hope this article will help you with your study of Python programming.

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.