我有一个元组列表,我试图根据最小值删除重复项:
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
我尝试了所有东西,但没能做到。
尝试以下代码:
# 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')]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句