首页 > 解决方案 > 在 Python 中搜索和过滤元组列表

问题描述

我有一个元组列表,我正在尝试根据最小值删除重复项:

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

我尝试了一切,但无法得到它。

标签: pythontuples

解决方案


试试下面的代码:

# 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')]

推荐阅读