"Tips" Python implementation list deduction for function return values

Source: Internet
Author: User

Background

Imagine a scenario where we define the function foo to generate a random code greater than 0. However, the function execution may have an exception, and for the exception we specify that the function returns-1.

In the case of batch processing, we want to get a collection of the return values of all successfully executed Foo functions, ignoring the case of return-1. The basic logic is as follows:

result = [] for in item_lst:    = foo (item)    if code! =-1 :        result.append (code)

Solutions for using list derivation

If you want to implement it in the form of a list deduction, there are several solutions:

Solution 1:

 for inch  forif code! =-1]

The return value of the function is obtained by using a list deduction, and then the filter is performed, and a two-time list deduction is required.

Solution 2:

 for inch if foo (item)! =-1]

Performs a list deduction once, but it is clear that the Foo function was executed two times. It can be problematic if the Foo function is time-consuming, or if multiple executions can have side effects.

Solution 3:

 for inch  for inch if Code! =-1]

Using a generator expression to handle intermediate results, without a temporary list, and based on iterators, is preferable to both methods.

Reference

    1. How to execute a filter by function return value in list comprehension?

"Tips" Python implementation list deduction for function return values

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.