我有一个元组列表,我正在尝试根据最小值删除重复项:
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
我尝试了所有但都无法完成。
答案 0 :(得分:1)
尝试以下代码:
# 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)
输出:
[('1', '111', '15'), ('4', '112', '40')]
答案 1 :(得分:1)
尝试一下:
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
将作为您的输出。
请注意,请勿将
list
之类的前缀名称用作变量名称。这些名字在python中意味着什么。
答案 2 :(得分:0)
仅出于理解的乐趣而无需导入的另一种可能性:
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}]
给予
[('5', '112', '10'), ('3', '111', '5')]