Python: sequence: Filtering sequence elements

Source: Internet
Author: User

problem: You have a data series that you want to use to extract the required values from or shorten the sequence

Answer

EG1: List derivation

The simplest way to filter sequence elements is to use list derivation. Like what:
>>> mylist = [1, 4,-5, 10,-7, 2, 3,-1]
>>> [n for N in mylist if n > 0]
[1, 4, 10, 2, 3]
>>> [n for N in MyList if n < 0]
[-5,-7,-1]

EG2: Generator expression iterations

a potential flaw in using list derivation is that it produces a very large result if the input is very large set, which consumes a lot of memory. If you are sensitive to memory, you can use the generator expression to iterate over the filtered elements. For example:
>>> pos = (n for n in mylist if n > 0)
>>> POS
<generator Object <genexpr> at 0x1006a0eb0>
>>> for x in POS:
... print (x)
...
1

4
10
2

3

Eg3:filter ()

Sometimes, filtering rules are complex and cannot be simply expressed in a list derivation or in a generator expression come on. For example, there are some exceptions or other complexities that need to be handled when filtering. You can put the filter code in a function, and then use the built-in filter () function

>>>values = [' 1 ', ' 2 ', '-3 ', '-', ' 4 ', ' N/A ', ' 5 ']
>>>def Is_int (val):
... try:
... x = Int (val)
.... return True
... except ValueError:
... return False
>>>ivals = List (filter (Is_int, values))
>>>print (Ivals)
# Outputs [' 1 ', ' 2 ', '-3 ', ' 4 ', ' 5 ']
The filter () function creates an iterator, so if you want a list, it's like an example then use list () to convert.

Python: sequence: Filtering sequence elements

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.