在Python中减去字符串列表
有时,在使用列表时,我们可能会遇到需要从另一个列表元素中删除一个列表元素的问题,即执行减法。这在许多领域都有应用。让我们讨论可以执行此任务的某些方式。
方法 #1:使用循环 + remove()
上述功能的组合可用于执行此任务。在此,我们使用 remove() 执行删除元素并使用循环检查类似元素。
Python3
# Python3 code to demonstrate working of
# Subtract String Lists
# using loop + remove()
# initialize lists
test_list1 = ["gfg", "is", "best", "for", "CS"]
test_list2 = ["preferred", "is", "gfg"]
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
# Subtract String Lists
# using loop + remove()
res = [ ele for ele in test_list1 ]
for a in test_list2:
if a in test_list1:
res.remove(a)
# printing result
print("The Subtracted list is : " + str(res))
Python3
# Python3 code to demonstrate working of
# Subtract String Lists
# using Counter() + elements()
from collections import Counter
# initialize lists
test_list1 = ["gfg", "is", "best", "for", "CS"]
test_list2 = ["preferred", "is", "gfg"]
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
# Subtract String Lists
# using Counter() + elements()
res = list((Counter(test_list1)-Counter(test_list2)).elements())
# printing result
print("The Subtracted list is : " + str(res))
输出
The original list 1 : ['gfg', 'is', 'best', 'for', 'CS']
The original list 2 : ['preferred', 'is', 'gfg']
The Subtracted list is : ['best', 'for', 'CS']
方法 #2:使用 Counter() + elements()
上述功能的组合提供了解决此问题的简写。在此,我们提取两个列表中元素的计数,然后使用 element() 通过提取它们来执行分离。
Python3
# Python3 code to demonstrate working of
# Subtract String Lists
# using Counter() + elements()
from collections import Counter
# initialize lists
test_list1 = ["gfg", "is", "best", "for", "CS"]
test_list2 = ["preferred", "is", "gfg"]
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
# Subtract String Lists
# using Counter() + elements()
res = list((Counter(test_list1)-Counter(test_list2)).elements())
# printing result
print("The Subtracted list is : " + str(res))
输出
The original list 1 : ['gfg', 'is', 'best', 'for', 'CS']
The original list 2 : ['preferred', 'is', 'gfg']
The Subtracted list is : ['best', 'for', 'CS']