Python - 从列表中的字符串中删除重复的单词
有时,在使用Python列表时,我们可能会遇到需要从字符串列表中删除重复单词的问题。当我们在数据域中时,这可以应用。让我们讨论可以执行此任务的某些方式。
方法 #1:使用set() + split()
+ 循环
上述方法的组合可用于执行此任务。在此,我们首先将每个列表拆分为组合词,然后使用 set() 来执行重复删除任务。
# Python3 code to demonstrate
# Remove duplicate words from Strings in List
# using loop + set() + split()
# Initializing list
test_list = ['gfg, best, gfg', 'I, am, I', 'two, two, three' ]
# printing original list
print("The original list is : " + str(test_list))
# Remove duplicate words from Strings
in List
# using loop + set() + split()
res = []
for strs in test_list:
res.append(set(strs.split(", ")))
# printing result
print ("The list after duplicate words removal is : " + str(res))
输出 :
The original list is : ['gfg, best, gfg', 'I, am, I', 'two, two, three']
The list after duplicate words removal is : [{'best', 'gfg'}, {'I', 'am'}, {'three', 'two'}]
方法 #2:使用列表理解 + set() + split()
这与上面的方法类似。不同之处在于我们使用列表推导而不是循环来执行迭代部分。
# Python3 code to demonstrate
# Remove duplicate words from Strings in List
# using list comprehension + set() + split()
# Initializing list
test_list = ['gfg, best, gfg', 'I, am, I', 'two, two, three' ]
# printing original list
print("The original list is : " + str(test_list))
# Remove duplicate words from Strings in List
# using list comprehension + set() + split()
res = [set(strs.split(", ")) for strs in test_list]
# printing result
print ("The list after duplicate words removal is : " + str(res))
输出 :
The original list is : ['gfg, best, gfg', 'I, am, I', 'two, two, three']
The list after duplicate words removal is : [{'best', 'gfg'}, {'I', 'am'}, {'three', 'two'}]