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

AI Hentai Generator
Generate AI Hentai for free.

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 and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

CentOS Installing Nginx requires following the following steps: Installing dependencies such as development tools, pcre-devel, and openssl-devel. Download the Nginx source code package, unzip it and compile and install it, and specify the installation path as /usr/local/nginx. Create Nginx users and user groups and set permissions. Modify the configuration file nginx.conf, and configure the listening port and domain name/IP address. Start the Nginx service. Common errors need to be paid attention to, such as dependency issues, port conflicts, and configuration file errors. Performance optimization needs to be adjusted according to the specific situation, such as turning on cache and adjusting the number of worker processes.
