Use the generator to rewrite the function method that directly returns the list. The generator returns the list.

Source: Internet
Author: User

Use the generator to rewrite the function method that directly returns the list. The generator returns the list.

This article is a learning note in the article "objective Python", recording the sample code and ideas.

If a function produces a series of results, the simplest way is to put these results in a list and return them.

For example, we want to locate the position of the first letter of each word in the string in the whole string:

def index_word(text):  result=[]  if text:    result.append(0)  for index,letter in enumerate(text):    if letter == ' ':      result.append(index+1)  return result

Use of this function:

  

This function has a clear idea, but the problems are code congestion and redundancy. Put all the results in the list before returning. If the input is huge, the program may run out of memory and crash.

It is better to use a generator to write this function. Data of any length does not affect the memory consumption during execution.

The generator is a function that uses the yield expression. When the generator function is called, it does not actually run, but returns the iterator. Every time the built-in next function is called on this iterator, The iterator will push the generator to the next yield expression. Each value transmitted by the generator to yield is returned to the caller by the iterator.

def index_word_iter(text):  if text:    yield 0  for index,letter in enumerate(text):    if letter == ' ':      yield index+1

Note that the iterator returned by the function can generate only one round of results. If the second round of iteration continues, no results will be returned.

The above Function Method to rewrite the direct return list using the generator is all the content shared by the editor. I hope to give you a reference and support for the help house.

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.