Using If-else in the Python list derivation

Source: Internet
Author: User

When dealing with automated mail data today, when data rows contain strings, the integer data obtained from hive is automatically converted into floating-point numbers, which can seriously affect aesthetics. Therefore, the idea is to use a list derivation to do the conversion, the digital data in all of the conversion to Integer, and the character data is left intact.


There are a total of two forms of the list deduction:

①[x for x in data if condition]

Here if the main function of the conditional judgment, the data only satisfies if conditions will be left, and finally unified into a data list

②[EXP1 if condition else EXP2 for x in data]

Here If...else is the main function of assignment, when the data in the value of the IF condition to do exp1 processing, otherwise, according to EXP2 processing, finally unified into a data list


Examples are as follows:

data = [' Driver ', ' 2017-07-13 ', 1827.0, 2058.0, 978.0, 1636.0, 1863.0, 2537.0, 1061.0]

(1) If I want to obtain a value greater than 2000 in the above list, this can be ① in the form of a list deduction:

[x for x in data if x > 2000]

The results are as follows (the string type data is considered an infinite number):

[' Driver ', ' 2017-07-13 ', 2058.0, 2537.0]

(2) To resolve the problem I mentioned above, you need to use the form of a list deduction ②

[Int (x) if type (x) = = Float else x for x in data]

Get results:

[' Driver ', ' 2017-07-13 ', 1827, 2058, 978, 1636, 1863, 2537, 1061]


This article is from the "Abe" blog, so be sure to keep this source http://abezoo.blog.51cto.com/7223683/1947675

Using If-else in the Python list derivation

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.