3

I have a list of tuples, I'm trying to remove duplicates based on minimum value :

a_list = [("1","111","15"),("2","111","10"),("3","111","5"),("4","112","40"),("5","112","10")]

Output : 
id id_client value2
1   111         15
2   111         10
3   111         5
4   112         40
5   112         10

Required Output
id id_client value2
3   111         5
5   112         10

I tried everything but couldn't get it.

3
  • 1
    Show what you tried and what went wrong. And I guess your first "Output" is actually "Input"? Commented Oct 14, 2019 at 13:01
  • I answered a question like this earlier today: stackoverflow.com/questions/58369762/… (Except, instead of appending to the list, just keep hold onto the minimum value.) Commented Oct 14, 2019 at 13:07
  • 1
    It's not recommended to use list as a name. Commented Oct 14, 2019 at 13:11

3 Answers 3

1

Try the following code:

# Input list
a_list = [("1","111","15"),("2","111","10"),("3","111","5"),("4","112","40"),("5","112","10")]

# Sort the list by the third value (index-2)
sorted_list = sorted(a_list, key=lambda x: int(x[2]))

# Track visited and repeated elements to only add the first tuple(x) with the smallest x[1]
visited = []

# New list to only append unique tuples
new_list = []

for i in sorted_list:
    if i[1] not in visited:
        new_list.append(i)
        visited.append(i[1])
print(new_list)

Output:

[('1', '111', '15'), ('4', '112', '40')]
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much , worked perfectly, Would you please explain this line sorted_list = sorted(a_list, key=lambda x: int(x[2])) ?
Sure. It sorts the list by the third element x[2] of the tuples inside. You can use key attribute of sorted function for such operations. Simply provide a function to the key attribute and it will do the rest. Check out this more detail here
1

Try this:

from itertools import groupby

new_l = []
for k,v in groupby(list, lambda x: x[1]):
    new_l.append(min(filter(lambda x:x[1]==k, list), key=lambda x:int(x[2])))

new_l will be your output.

Note that do not use pre-defiend names like list as a variable name. those names are mean something in python.

1 Comment

Thank you so much , worked perfectly, I changed list to a_list in the question above
0

Another possibility without importing, just because comprehension is fun:

lst = [("1","111","15"),("2","111","10"),("3","111","5"),("4","112","40"),("5","112","10")] 

[min((x for x in lst if x[1] == client), key=lambda x: int(x[2])) for client in {row[1] for row in lst}]

gives

 [('5', '112', '10'), ('3', '111', '5')]

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.