-1

Suppose if i have list input_list=["Name","Age","Address","nAme","Father","NAME","AGE"]

  • I have "name" multiple times but while checking I don't want it to be case sensitive. if there is duplicate add 1 , 2 etc.

  • I am trying to remove Duplicates i want to add NaMe, Name1,NAME2 but order should be same

    can you please help me achieve this output.

I want output final_list=["Name","Age","Address","nAme1","Father","NAME2","AGE1"]

kakaji
  • 161
  • 9
  • I think this was closed in error - OP doesn't want to remove duplicates but rename them (appending a number). The post perhaps should make this clearer? – Jack Deeth Feb 13 '22 at 18:04

1 Answers1

1

Here's one way to do it.

  1. Make a set of lowercased entries from that list
lowered_set = {word.lower() for word in input_list}
  1. Make a dict with that set as keys
occurrences = {word: 0 for word in lowered_set}
  1. Walk the input_list, append count if the word was used already, and increment the count:
output_list = []
for word in input_list:
    lowered = word.lower()
    previous = occurrences[lowered]
    occurrences[lowered] += 1
    if previous:
        output_list.append(f"{word}{previous}")
    else:
        output_list.append(word)

There's surely a better way, though

Jack Deeth
  • 3,062
  • 3
  • 24
  • 39
  • (this doesn't work if your input_list has words ending with numbers… `["name", "nAmE1", "NAME", "namE"]` will become `["name", "nAmE1", "NAME1", "namE2"]` – Jack Deeth Feb 13 '22 at 18:09