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

Time:04-03

Below is the array of words I'm having

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

And I want to make it That has only unique words. Below is how I want it to be after processing

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

Simply I want to have unique set of words.

CodePudding user response:

You can use a loop:

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

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

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

Or, if order matters:

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

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

functional variant
from itertools import chain
set(chain.from_iterable(map(str.split, l)))

CodePudding user response:

Try this

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, 

original post at GeekforGeeks https://www.geeksforgeeks.org/python-get-unique-values-list/

  • Related