📜  Python - 删除包含列表字符的单词

📅  最后修改于: 2022-05-13 01:55:32.112000             🧑  作者: Mango

Python - 删除包含列表字符的单词

有时,在数据过滤过程中,我们会遇到一个问题,即我们需要删除由某些字母组成的单词。这种应用在数据科学领域很常见。让我们讨论可以执行此任务的某些方式。

方法 #1:使用all() + 列表推导
上述方法的组合可用于执行此任务。在此,我们只在每个列表中使用 all() 检查所有列表字符,并过滤掉具有任何一个字符。

# Python3 code to demonstrate 
# Remove words containing list characters
# using list comprehension + all()
from itertools import groupby
  
# initializing list 
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
  
# initializing char list 
char_list = ['g', 'o']
  
# printing original list
print ("The original list is : " + str(test_list))
  
# printing character list
print ("The character list is : " + str(char_list))
  
# Remove words containing list characters
# using list comprehension + all()
res = [ele for ele in test_list if all(ch not in ele for ch in char_list)]
  
# printing result 
print ("The filtered strings are : " + str(res))
输出 :
The original list is : ['gfg', 'is', 'best', 'for', 'geeks']
The character list is : ['g', 'o']
The filtered strings are : ['is', 'best']

方法#2:使用循环
这是可以执行此任务的蛮力方法。在此我们使用循环和条件语句来执行此任务。

# Python3 code to demonstrate 
# Remove words containing list characters
# using loop
from itertools import groupby
  
# initializing list 
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
  
# initializing char list 
char_list = ['g', 'o']
  
# printing original list
print ("The original list is : " + str(test_list))
  
# printing character list
print ("The character list is : " + str(char_list))
  
# Remove words containing list characters
# using loop
res = []
flag = 1
for ele in test_list:
    for idx in char_list:
        if idx not in ele:
            flag = 1
        else:
            flag = 0  
            break
    if(flag == 1):
        res.append(ele)  
  
# printing result 
print ("The filtered strings are : " + str(res))
输出 :
The original list is : ['gfg', 'is', 'best', 'for', 'geeks']
The character list is : ['g', 'o']
The filtered strings are : ['is', 'best']