0

So I was working on a problem in which, given a list of tuples, I had to return a new list only containing the elements in which the first element of the tuple isn't duplicated. I had no problem removing duplicates but my problem is removing the original element as soon as a duplicate is found. eg.

inputList = [("test0", 20), ("test1", 25), ("test0", 30)]

This should return

[("test1", 25)]

I have after my troubles gotten it to work, however I fear my code is bad and that there is a much easier way to perform what I have done. I've done it by first removing duplicates

visited = set()
marked = []
output = []
for key, value in resList:
    if not key in visited:
        visited.add(key)
        output.append((key, value))
    else:
        marked.append(key)

I then check my new output list against my marked list

resList = []
for mark in marked:
    for i in range(len(output)):
        if mark != output[i][0]
            resList.append(output[i])

4 Answers 4

1

You can do it simply using list comprehension like so:

list1 = [x[0] for x in inputList]

outputList = [(x, y) for x, y in inputList if list1.count(x) == 1]

Hope it helps :)

Sign up to request clarification or add additional context in comments.

Comments

0

First count how many times the first element appears in the list. For this purpose we use a dictionary d. Then use a simple list comprehension.

d = dict()
for x, y in inputList:
  d[x] = d.get(x, 0) + 1
outputList = [(x, y) for x, y in inputList if d[x] == 1]

Comments

0

Use a Counter to count occurrences in inputList, then filter out any items that occur more than once.

from collections import Counter

count = Counter(t[0] for t in inputList)
result = [t for t in inputList if count[t[0]] == 1]

print(result)  # -> [('test1', 25)]

Comments

0

Add it to the output if it is not yet there. If it's already there, remove it and blacklist it (to avoid adding it again).

inputList = [("test0", 20), ("test1", 25), ("test0", 30)]

removed = set()
output = []
for key, value in inputList:
    keyfound = False
    for refkey, refvalue in output:
        if key == refkey:
            keyfound = True
            removed.add(key)
            output.remove((refkey, refvalue))
    if keyfound == False and key not in removed:
        output.append((key, value))

print(output)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.