How to filter elements in a sequence in Python
The content of this article is about how Python filters elements in a sequence. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
1. Requirements
The sequence contains some data, we need to extract the values or delete the sequence according to certain standards,
2. Solution
To filter data in a sequence, usually the easiest way is to use a list comprehension.
For example:
myList=[1,4,-5,10,-7,2,3,-1] print([n for n in myList if n>0]) print([n for n in myList if n<0])
Result:
[1, 4, 10, 2, 3] [-5, -7, -1]
A potential disadvantage of using list comprehensions is that if the original input is very large, doing so may produce a huge the result of. If this is a problem you need to consider, you can use a generator expression to generate filtering results through an iterative method, for example:
myList=[1,4,-5,10,-7,2,3,-1] pos=(n for n in myList if n >0) for x in pos: print(x)
Result:
1 4 10 2 3
Sometimes the filtering criteria cannot be simple expressed in a list comprehension or generator expression. For example: Suppose the screening process involves exception handling or other complex details. Based on this, you can put the code that handles the filtering logic into a separate function, and then use the built-in filter() function to process it. The example is as follows:
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)
Result:
['1', '2', '-3', '4', '5']
filter() An iterator is created, so if we want the result as a list, make sure to include list(), like in the example.
3. Analysis
List comprehensions and generator expressions are usually the simplest and most direct way to filter data. In addition, they also have the ability to transform data simultaneously. For example:
import math myList=[1,4,-5,10,-7,2,3,-1] print([math.sqrt(n) for n in myList if n>0])
Result:
[1.0, 2.0, 3.1622776601683795, 1.4142135623730951, 1.7320508075688772]
Regarding filtering data, one situation is to replace values that do not meet the criteria with new values instead of discarding them. For example. In addition to finding positive integers, we also want to replace values that do not meet the requirements within a specified range. Often this can be easily accomplished by moving the filter criteria into a conditional expression, like this:
myList=[1,4,-5,10,-7,2,3,-1] print([n if n>0 else 0 for n in myList]) print([n if n<0 else 0 for n in myList])
Result:
[1, 4, 0, 10, 0, 2, 3, 0] [0, 0, -5, 0, -7, 0, 0, -1]
Another filtering tool worth mentioning is itertools .compress(), which accepts an iterable and a sequence of Boolean selectors as input. On output, it gives all iterable object elements that are True in the corresponding Boolean selector. This is useful if you want to apply the results of a filter on one sequence to another related sequence.
For example:
from itertools import compress address=[ '5412 N CLARK1', '5148 N CLARK2', '5800 E CLARK3', '2122 N CLARK4', '5645 M CLARK5', '1060 W CLARK6', ] counts=[0,3,10,4,1,7] #构建一个列表,它相应的count值要大于5 more5=[n>5 for n in counts] print(more5) print(list(compress(address,more5)))
Result:
[False, False, True, False, False, True] ['5800 E CLARK3', '1060 W CLARK6']
The key here is to first create a Boolean sequence to represent which element can meet our conditions, and then compress() function Select the corresponding elements whose Boolean value is True.
Same as the filter() function, compress() will return an iterator under normal circumstances. Therefore, if necessary, you have to use list() to convert the result into a list.
The above is the detailed content of How to filter elements in a sequence in Python. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.
