Python|删除包含给定字符串字符的列表元素
有时,在使用Python列表时,我们可能会遇到问题,我们需要执行删除列表中至少包含一个字符串字符的所有元素的任务。这可以在日常编程中应用。让我们讨论可以执行此任务的某些方式。
方法#1:使用循环
这是可以执行此任务的蛮力方式。在此,我们迭代所有列表元素并使用循环检查是否出现任何字符。
# Python3 code to demonstrate working of
# Remove List elements containing String character
# Using loop
# initializing list
test_list = ['567', '840', '649', '7342']
# initializing string
test_str = '1237'
# printing original list
print("The original list is : " + str(test_list))
# Remove List elements containing String character
# Using loop
res = []
for sub in test_list:
flag = 0
for ele in sub:
if ele in test_str:
flag = 1
if not flag:
res.append(sub)
# printing result
print("The list after removal : " + str(res))
输出 :
The original list is : ['567', '840', '649', '7342']
The list after removal : ['840', '649']
方法#2:使用列表推导
这是执行此任务的另一种方式。这与上述方法类似。在这种情况下,我们以与上述类似的方式执行任务,就像一个班轮一样。
# Python3 code to demonstrate working of
# Remove List elements containing String character
# Using list comprehension
def check_pres(sub, test_str):
for ele in sub:
if ele in test_str:
return 0
return 1
# initializing list
test_list = ['567', '840', '649', '7342']
# initializing string
test_str = '1237'
# printing original list
print("The original list is : " + str(test_list))
# Remove List elements containing String character
# Using list comprehension
res = [ele for ele in test_list if check_pres(ele, test_str)]
# printing result
print("The list after removal : " + str(res))
输出 :
The original list is : ['567', '840', '649', '7342']
The list after removal : ['840', '649']