Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python returning unique words from a list (case insensitive)

I need help with returning unique words (case insensitive) from a list in order.

For example:

def case_insensitive_unique_list(["We", "are", "one", "we", "are", "the", "world", "we", "are", "THE", "UNIVERSE"])

Will return: ["We", "are", "one", "the", "world", "UNIVERSE"]

So far this is what I've got:

def case_insensitive_unique_list(list_string):

uppercase = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
lowercase = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]

temp_unique_list = []

for i in list_string:
    if i not in list_string:
        temp_unique_list.append(i)

I am having trouble comparing every individual words from the temp_unique_list whether that word repeats itself or not. For example: "to" and "To" (I am assuming range function will be useful)

And to make it return the word that comes first from the original list that function will take in.

How would I do this using the for loop?

like image 836
user927584 Avatar asked May 05 '14 13:05

user927584


1 Answers

You can do this with the help of a for loop and set data structure, like this

def case_insensitive_unique_list(data):
    seen, result = set(), []
    for item in data:
        if item.lower() not in seen:
            seen.add(item.lower())
            result.append(item)
    return result

Output

['We', 'are', 'one', 'the', 'world', 'UNIVERSE']
like image 82
thefourtheye Avatar answered Oct 02 '22 14:10

thefourtheye