Fundamentals 4 min read

How to Filter List Elements by Keywords in Python: Two Simple Methods

This article explains a Python fan's question about extracting list items that contain specific keywords, presents two practical solutions—regular list indexing and using the operator module—and shows the resulting outputs with code snippets and screenshots.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
How to Filter List Elements by Keywords in Python: Two Simple Methods

Introduction

A fan asked how to filter a list of titles so that only those containing both "python" and "应用" (application) remain. The issue arises because the titles are stored as nested lists, requiring an extra extraction step.

Method 1: Regular reading

# -*- coding: utf-8 -*-
keywordlist = ['python', '应用']
title = [['人生苦短,我应用python'], ['Rick Xiang 666'], ['歪歪nb'], ['为才哥打call'], ['网络爬虫的应用']]
for luwen in title:
    if keywordlist[0] in luwen[0] and keywordlist[1] in luwen[0]:
        print(luwen)

Running the code prints the matching sub‑list:

Method 2: Using the operator library

# -*- coding: utf-8 -*-
import operator
keywordlist = ['python', '应用']
title = [['人生苦短,我应用python'], ['Rick Xiang 666'], ['歪歪nb'], ['为才哥打call'], ['网络爬虫的应用'], ['python爬虫与数据挖掘']]
for luwen in title:
    if operator.contains(luwen[0], keywordlist[0]) and operator.contains(luwen[0], keywordlist[1]):
        print(luwen)

The execution yields the matching entry as shown:

Conclusion

The two approaches successfully locate list elements that contain the required keywords. While the article demonstrates only these two methods, other techniques are possible, and readers are encouraged to experiment further.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonOperatorCode ExampleListkeyword-search
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.