Python代码优化需求:实现列表元素按子串匹配移除
Fixing Substring-Based Filtering in Your Python Script
Hey there! Let's tweak your code so it removes any email from mylist that contains any substring from myNames, not just exact matches. Here's how to do it:
Updated Full Code
import pandas as pd # Load and clean email list from Excel failas = 'test.xlsx' df = pd.read_excel(failas) df2 = df.drop_duplicates() mylist = df2['EMAILS'].tolist() # Load exclusion substrings from text file with open('test.txt', 'r') as f: myNames = f.read().splitlines() # Filter out any email containing any substring from myNames # We keep emails where NONE of the substrings are present Output = [x for x in mylist if all(sub not in x for sub in myNames)] # Print results for verification print("Initial list is :", mylist) print("Exclusion substrings :", myNames) print("List after removing elements is :", Output)
Key Changes Explained
The main fix is in the list comprehension line:
- Original logic:
[x for x in mylist if x not in myNames]checks for exact matches only. - New logic:
[x for x in mylist if all(sub not in x for sub in myNames)]checks that none of the substrings frommyNamesappear in the email.
Breaking down the new condition:
all(...)ensures every substring inmyNamesfails thesub not in xcheck (meaning no substring is present in the email)sub not in xchecks if a single substring is not contained within the email string
Optional Optimizations
If you need case-insensitive matching (e.g., exclude emails containing "Tr" even if the substring is "tr"), modify the condition to:
Output = [x for x in mylist if all(sub.lower() not in x.lower() for sub in myNames)]
Also, if your email list might have None values, add a check to avoid errors:
Output = [x for x in mylist if x is not None and all(sub not in x for sub in myNames)]
内容的提问来源于stack exchange,提问作者AndriusJ
相关产品推荐
相关产品推荐

