Reputation: 715
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.
Upvotes: 3
Views: 63
Reputation: 5149
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')]
Upvotes: 0
Reputation: 11073
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.
Upvotes: 1
Reputation: 5004
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')]
Upvotes: 1