如何通过使用 python 删除重复项从数组中获取唯一的单词集

How to get unique set of words from an array by removing duplicates using python

下面是我的单词数组

l = ['Australian Cricket Team',
     'Cricket Team Australian',
     'Won Against England',
     'Against England Team']

我想让它只有独特的词。下面是我希望它在处理后的样子

['Australian', 'Cricket' ,'Team', 'Won',  'Against', 'England']

就是想拥有独一无二的词组。

您可以使用循环:

l = ['Australian Criket Team', 'Cricket Team Australian', 'Won Against England', 'Against England Team']

set(w for s in l for w in s.split())

输出:{'Against', 'Australian', 'Cricket', 'Criket', 'England', 'Team', 'Won'}

或者,如果顺序很重要:

list(dict.fromkeys(w for s in l for w in s.split()))

输出:['Australian', 'Criket', 'Team', 'Cricket', 'Won', 'Against', 'England']

功能变体
from itertools import chain
set(chain.from_iterable(map(str.split, l)))

试试这个

def unique(list1):
 
    # initialize a null list
    unique_list = []
     
    # traverse for all elements
    for x in list1:
        # check if exists in unique_list or not
        if x not in unique_list:
            unique_list.append(x)
    # print list
    for x in unique_list:
        print x, 

原 post 在 GeekforGeeks https://www.geeksforgeeks.org/python-get-unique-values-list/